使用指针处理字符串

Working with strings using pointers

本文关键字:字符串 处理 指针      更新时间:2023-10-16

大家好,这是我的代码:

#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)

我做错了什么?

Btw。我在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不再将指针作为参数,而是要打印的字符串的常量引用。

您必须更改主菜单才能调用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;
    }
}