如何使用std::cin从单行输入中获取最多3个不定数量的参数并解析
实现方案
问题原因
std::cin 的 >> 提取运算符默认会忽略前导空白字符,且未读取到有效内容时会持续阻塞等待用户输入,不会主动将未赋值的字符串变量置空,因此你原先连写三个 >> 的写法必须输入3个值才会继续执行。
实现代码
你可以先读取完整的一行输入,再通过字符串流拆分单词,完全保留你需要的arg1/arg2/arg3调用方式,不需要逐次提示逻辑:
#include <iostream> #include <string> #include <sstream> using namespace std; int main() { string arg1, arg2, arg3; cout << "insert your words: " << endl; // 先读取完整的一行输入,读到换行就停止,不会阻塞等待更多内容 string line; getline(cin, line); // 将整行内容传入字符串流,后续从流中提取单词 istringstream line_stream(line); // 从字符串流中提取单词,最多提取3个,流空后后续提取操作不会修改变量 line_stream >> arg1 >> arg2 >> arg3; // 后续判断逻辑和你原先的代码完全一致 if (arg2.empty()) { cout << "you inserted one word" << endl; if(arg1 == "WORD") { cout << "first word is WORD" << endl; } else { cout << "first word is not WORD " << endl; } } else if (arg3.empty()) { cout << "you inserted two words" << endl; } else { cout << "you inserted 3 words" << endl; } // 如果用户输入超过3个单词,超出部分会自动忽略,符合最多3个的要求 return 0; }
注意事项
如果你的程序在调用getline之前有过其他cin >>的操作,需要先调用cin.ignore()清理输入缓冲区中残留的换行符,避免getline读取到空行。
内容的提问来源于stack exchange,提问作者YarsaB_
相关产品推荐
相关产品推荐

