【问题标题】:How to I read in a line and delimit it with '!!" in C++?如何在 C++ 中读取一行并用 '!!" 分隔它?
【发布时间】:2013-09-17 14:08:29
【问题描述】:

我曾尝试使用getline(),但将delimiter 设置为“!!”会导致程序无法编译。我需要将字符串读入一个名为messages的字符串变量中。我的代码看起来像这样...帮助?

cout << "Enter the message> ";
getline(cin, message, "!!");

【问题讨论】:

  • 您不能在getline 中使用多字符分隔符 - 它需要一个分隔符 character (不是分隔符字符串),因此编译错误(无法使用字符串预计有一个字符的地方)。有关更多信息,请参阅here - 没有采用分隔符字符串的重载。您需要选择 1 个字符的分隔符,或者使用不同的方法来处理您的输入流。

标签: c++ string delimiter getline cin


【解决方案1】:

您没有正确使用 std 函数。您正在尝试为分隔符而不是字符传递字符串。如果那是您需要的分隔符,getline 不会帮助您。

http://www.cplusplus.com/reference/string/string/getline/

在这里您可以找到您想要实现的工作代码:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string message;
    cout << "Enter the message>";
    cin >> message;
    cout << message.substr(0, message.find("!!")) << endl;

    return 0;
}

您需要针对您的场景运行此命令或类似命令:g++ main.cpp &amp;&amp; a.out

输出是:

Enter the message>sadfsadfdsafsa!!4252435
sadfsadfdsafsa

【讨论】:

    【解决方案2】:
    str.substr(0, inStr.find("!!"));
    

    示例:http://codepad.org/gPoqJ1Ie

    Explanation

    dmitri 解释了错误发生的原因。

    【讨论】:

      【解决方案3】:

      getline() 接受 char 作为分隔符,“!!”是一个字符串

      istream& getline (istream& is, string& str, char delim);
      

      这就是你的代码无法编译的原因

      1. 逐个字符读取输入字符并自行标记。 std::string::find 方法 会有所帮助,或者您可以查看boost.tokenizer
      2. 使用“!”作为 getline() 或 getdelim() 中的参数读取字符串并等待下一个 '!',如果不是 '!',则继续累积字符串

      【讨论】:

        猜你喜欢
        • 2015-12-03
        • 2015-10-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-15
        • 1970-01-01
        • 2020-11-21
        相关资源
        最近更新 更多