将元素添加到矢量,直到用户不再需要?
Adding elements to a vector until the user doesn't want to any more?
int userInput = 0;
vector<int> userVector;
cout << "Input the numbers you would like in the vector. " << endl;
bool flag = true
while (flag == true)
{
cin >> userInput;
}
我想让程序做的是,用户向向量输入数字,直到他们满意为止。我认为停止循环的条件可以是输入任何字符/字符串,但为了简洁起见,也许可以是'no ',' quit '或'n '。我也不确定如何将userInput集成到向量中。
EOF就是为此而发明的。当用户键入Ctrl+D (Linux)或Ctrl+Z (Windows)时,或者当到达文件末尾时(如果输入来自文件),则会发生此错误。没有必要再编一个哨兵值
while (cin >> userInput) {
// ...
}
当输入结束或提取失败时,此循环将停止。
我会尝试一种稍微不同的方法,以字符串形式获得输入。它允许更健壮的错误处理,以及允许终止输入值。
std::string userInput;
std::vector<int> userVector;
std::cout << "Input the numbers you would like in the vector (Q to quit). " << std::endl;
while (getline(cin, userInput))
{
// Ignore blank lines
if (userInput.empty())
continue;
if (userInput[0] == 'Q' || userInput[0] == 'q')
break;
try
{
userVector.push_back(stoi(userInput));
}
catch (const std::invalid_argument&)
{
std::cout << "That's not a valid number!" << std::endl;
}
}
相关文章:
- C++如何通过用户输入删除列表元素
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 使用用户定义函数的字符串反转
- 用户定义函数中的指针和输入
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- 如何只允许用户输入正整数
- C++如何计算用户输入的数字中的偶数位数
- 通过for循环使用用户输入填充列表
- 这是我尝试让用户将值输入到数组中.然后将其隐藏为大量的星号
- 在C++中,我如何接受不同于同一行的用户输入
- 当用户超过按钮点击限制时报告
- Visual C++(VS2017)中用户定义的转换不明确
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 当用户键入分隔符时,停止getline()输入
- 通过错误处理,在C++中可靠地获得用户十六进制输入
- RegGetValue在当前用户下找不到名称
- 将元素添加到矢量,直到用户不再需要?