【问题标题】:How to read user input with delimiting character while retaining white spaces as input in c++如何在 C++ 中保留空格作为输入时使用定界字符读取用户输入
【发布时间】:2015-05-07 16:58:42
【问题描述】:

我一直在处理所需的庄园中的用户输入。我需要输入例如“Name100/Some other name”。使用下面的代码,我可以将直到“/”的所有内容分配给变量 input1,但是我无法将整个字符串“其他名称”放入变量 input2,只分配了第一个单词。感谢您的帮助。

string input;
string input1;
string input2;

cout << "Please enter a Name and Another Name" << endl;     
cin >> input;

stringstream ss(input);
getline(ss, input1, '/');
getline(ss, input2);

cout << input1 << endl;
cout << input2 << endl;

输出:

请输入一个名字和另一个名字

名字100

一些

【问题讨论】:

    标签: c++ string input stream


    【解决方案1】:

    代替

    cin >> input;
    

    使用

    std::getline(std::cin, input);
    

    第一个将在第一个空白字符处停止读取。第二个将读取整行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-30
      • 1970-01-01
      • 2013-06-07
      • 2023-01-29
      • 2011-10-20
      相关资源
      最近更新 更多