我试图编写一个简单的循环,它接受一个字符串并遍历所述字符串的每个字符,并将其存储在另一个字符串中(每次都是相同的字符串)。我想使用这个循环来执行简单的任务,例如反向显示一个单词,或者在一个单独的行中显示每个字符(下面提供的示例就是从这里来的)。我的代码是这样的:
#include <string>
using namespace std;
int main(){
c++
string word;
string ch;
cout << "Please enter a word." << endl;
cin >> word;
int wordlength;
int i;
wordlength = size(word);
for (i = 0; i < wordlength; i++) {
word.copy(ch, 1, i);
cout << ch << endl;
}
}
但是,每当我使用这段代码时,我都会得到标题中的错误:
“从'std::string‘到'const *’不存在适当的转换函数”
我做错了什么?
发布于 2019-12-25 02:44:38
只需使用字符串
#include <string>
using namespace std;
string word;
char *c;
cout << "Please enter a word." << endl;
cin >> word;
int wordlength, i;
wordlength = word.size();
for (i = 0; i < wordlength; ++i) {
ch = word[i];
cout << ch << endl;
}
无论哪种方式都可以工作,word[i] = ch;
发布于 2019-12-25 01:45:50
字符串大小:
wordlength = word.size();
字符串::复制应该是:
char ch;
....
word.copy(&ch, 1, i);
发布于 2019-12-25 01:40:49
来自c++引用
size_t拷贝(char* s,size_t len,size_t pos = 0) const;
本质上,复制需要一个char指针/数组作为它的第一个arg,但是您放置了一个字符串,所以它抛出了一个错误。
https://stackoverflow.com/questions/59474515
复制相似问题