我怎么能只用一次cin

How can I use cin only once?

本文关键字:一次 cin 怎么能      更新时间:2023-10-16

我想在一行中从用户那里获得多个数字,并将其存储在向量中。我就是这样做的:

vector<int> numbers;
int x;
while (cin >> x)
    numbers.push_back(x);

然而,在输入我的号码并按下回车键后,就像这样:

1 2 3 4 5

它将数字放入向量中,然后等待更多的输入,这意味着我必须输入Ctrl+Z才能退出循环。如何在获得一行整数后自动退出循环,这样就不必输入Ctrl+Z

实现这一点的最简单方法是使用字符串流:

#include <sstream>
//....
std::string str;
std::getline( std::cin, str ); // Get entire line as string
std::istringstream ss(str);
while ( ss >> x ) // Now grab the integers
    numbers.push_back(x); 

要验证输入,在循环后可以执行以下操作:

if( !ss.eof() )
{
   // Invalid Input, throw exception, etc
}
while (std::cin.peek() != 'n') {
    std::cin >> x;
    numbers.push_back(x);
}

更新

while (std::cin.peek() != 'n') {
    std::cin >> x;
    numbers.push_back(x);
    // workaround for problem from comment
    int tmp;
    while (!isdigit(tmp = std::cin.peek()) && tmp != 'n') {
      std::cin.get();
    }
}
相关文章: