将元素添加到矢量,直到用户不再需要?

Adding elements to a vector until the user doesn't want to any more?

本文关键字:不再 用户 元素 添加      更新时间:2023-10-16
 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;
    }
}