大家好,这是我的代码:
#include <iostream>
#include <string>
using namespace std;
void writeDown(string*t)
{
for (int i = 0; *(t+i)!=NULL; i++)
{
cout << *(t+i) <<endl;
}
}
int main()
{
string t;
getline(cin, t);
string *wsk = &t;
writeDown(wsk);
return 0;
}
所以我只是插入一个字符串,程序应该cout<<
它的每个字符都在一个新行中。但这是弹出的内容:
binary '!=' : no operator found which takes a left-hand operand of type 'std::string' (or there is no acceptable conversion)
我做错了什么?
顺便说一句。我在 VS 2013 中为 Win Desktop 工作(顺便说一句。第 2 卷 - 它是 C++ 编码的良好环境吗? - 2015 年,但它在我的笔记本电脑上变慢了)
最佳答案
好吧,代码在很多层面上都很糟糕,但为了保持简单并回答您的问题,我可能会使用迭代器。如果您使用的是 C++,请忘掉旧的 C 风格。
试试这个:
void writeDown(const string & t)
{
for (string::const_iterator it = t.begin();
it != t.end();
++it)
{
cout << *it << endl;
}
}
请注意,writeDown
不再将指针作为参数,而是对要打印的字符串的常量引用。
你必须改变你的 main 来调用 writeDown
:
string t;
getline(cin, t);
writeDown(t);
如果您坚持使用“数组”方法,您将不得不像这样使用它,但是......
void writeDown(const string & t)
{
for (int i = 0; t.c_str()[i] != NULL; i++)
{
cout << t.c_str()[i] << endl;
}
}
关于c++ - 使用指针处理字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34713406/