C++ 检查缓冲区中是否有任何内容
我正在编写一个程序,要求用户通过控制台输入一些输入。有时是一个字符串,有时是两个字符串。我需要能够检查是否输入了一个或两个字符串。我目前正在尝试的是:C++ 检查缓冲区中是否有任何内容,c++,string,input,C++,String,Input,我正在编写一个程序,要求用户通过控制台输入一些输入。有时是一个字符串,有时是两个字符串。我需要能够检查是否输入了一个或两个字符串。我目前正在尝试的是: string s1,s2; cin >> s1; // do some operations on s1 (nothing using cout/cin) if(thereIsASecondString()) { //do some operations on the second string } 我希望有某种函数可以
string s1,s2;
cin >> s1;
// do some operations on s1 (nothing using cout/cin)
if(thereIsASecondString()) {
//do some operations on the second string
}
我希望有某种函数可以用来查看是否输入了第二个字符串。在搜索之后,我发现了像cin.eof()
,cin.peek()
和cin.rdbuf
这样的东西,但我要么不能正确使用它们,要么它们不适合使用。有人能告诉我是否有一个函数可以实现我需要的功能(检查在第一个字符串之后是否输入了任何内容)
或者,我可以使用getline(),然后循环遍历它,并将其拆分为两个字符串,其中包含空格(如果有)。这是更好的选择吗?我仍然想知道是否可以使用cin。将
istringstream
与getline
结合使用:
string line;
if (!getline(cin, line)) {
// handle error...
}
istringstream iss(line);
string s1, s2;
if (!(iss >> s1)) {
// we didn't even get one string, handle error...
}
// do something with s1
if (iss >> s2) {
// there was a second string, do something with it
}