我怎么能只用一次cin
How can I use cin only once?
我想在一行中从用户那里获得多个数字,并将其存储在向量中。我就是这样做的:
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();
}
}
相关文章:
- 我是否需要在下一次转移时将所有权*转移回转移队列
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 在C++中一次将矢量值写入多个文件
- 循环中的条件:为什么每次都调用strlen(),而vector.size()只调用一次
- 为什么 zlib 放气初始化调用一次不起作用?
- 在一次迭代中从 txt 文件中读取多行
- 为什么无论你输入什么,这"while(cin.get(str,3))"只运行一次?
- 在头文件和 cpp 文件中使用一次 #pragma 时出现结构重定义错误
- 有没有办法一次声明相同类型的多个对象,并通过一个表达式立即使用相同的右值初始化它们?
- 高级选择排序 - 在一次迭代中搜索两个元素
- 具有相同特征的两个对象是否只在内存中存储一次?无论定义它们的函数是什么,都是不同的
- 为什么我的 cout 一次执行,尽管 cin 应该在两者之间读取?
- 当我输入一个字母时,cin 输入(输入是一个 int),而不是打印错误一次,它打印正确一次,然后在循环的其余部分打印 i
- 为什么cin.rdbuf()->sbumpc()在循环中只要求我输入一次?
- 如何从文件中一次读取一个输入,类似于在c++中使用cin/scanf从控制台读取输入
- cin.ignore() 输入两次以获得一次暂停
- 当用户输入错误输入时,一次清除 cin 中的整行而不是一个字符
- 如何使用 cin 一次存储一个值
- std::getline 在最后一次出现分隔符后跳过来自 std::cin 的输入,但不跳过来自 std::istrin
- 我怎么能只用一次cin