【问题标题】:Working with strings using pointers使用指针处理字符串
【发布时间】:2016-01-11 02:39:44
【问题描述】:

大家好,这是我的代码:

#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&lt;&lt; 中的每个字符都放在一个新行中。但这是弹出的内容:

binary '!=' : no operator found which takes a left-hand operand of type 'std::string' (or there is no acceptable conversion)

我做错了什么?

顺便说一句。我正在为 Win Desktop 使用 VS 2013(顺便说一句。第 2 卷 - 它是 C++ 编码的良好环境吗? - 2015 年了,但在我的笔记本电脑上速度很慢)

【问题讨论】:

  • 您似乎正试图将std::string* 视为char*。这不是它的工作原理,它们是非常不同的东西。
  • 糟糕,也许吧,那么正确的做法是什么?
  • 如果std::stringconst char* 类似,那么std::string* 与什么类似?
  • @Frynio 如果我的回答对您有用,您会愿意将其标记为已接受吗?

标签: c++ string pointers


【解决方案1】:

好吧,代码在很多层面上都很糟糕,但为了保持简单并回答您的问题,我可能会使用迭代器。如果您使用 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;
    }
}

【讨论】:

  • 当我使用asterix &amp;* 作为参数时,它是一样的吗(“相同”是指速度)?
  • @Frynio 过早的优化是愚蠢的根源。专注于编写易于理解和维护的代码,然后根据分析结果进行优化。
  • 谢谢。我总是会做一些不重要的事情,专注于它们,而不是我的主要目标
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-05
  • 2018-02-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多