如何在 c++ 中读取带有分隔字符的用户输入,同时保留空格作为输入

How to read user input with delimiting character while retaining white spaces as input in c++

本文关键字:输入 用户 保留 空格 字符 c++ 读取 分隔      更新时间:2023-10-16

我坚持在所需的庄园中处理用户输入。我需要输入例如"Name100/其他名称"。使用下面的代码,我可以将所有内容分配给变量 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

一些

而不是

cin >> input;

std::getline(std::cin, input);
第一个

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