5

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

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

3 回答 3

2

您没有正确使用 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 && a.out

输出是:

Enter the message>sadfsadfdsafsa!!4252435
sadfsadfdsafsa
于 2013-09-13T02:07:23.460 回答
1
str.substr(0, inStr.find("!!"));

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

解释

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

于 2013-09-13T02:11:47.813 回答
0

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

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

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

  1. 逐个字符地读取输入字符并自己对其进行标记。std::string::find方法会有所帮助,或者您可以查看boost.tokenizer
  2. 采用 '!' 作为 getline() 或 getdelim() 中的参数来读取字符串并等待下一个 '!',如果不是 '!' 则继续累积字符串
于 2013-09-13T01:54:15.187 回答