C++ 用cin检测输入结束
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21420352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
detecting end of input with cin
提问by Celeritas
I want to read a line of integers from the user. I'm not sure how to check to see if the input has ended. For example I want to be able to do something like
我想从用户那里读取一行整数。我不确定如何检查输入是否已结束。例如,我希望能够做类似的事情
int x[MAX_SIZE];
int i = 0;
while(cin.hasNext())
{
cin >> x[++i];
}
Example input: 2 1 4 -6
示例输入:2 1 4 -6
how can I check to see if there's any more for cin
to take?
我怎样才能检查是否还有其他东西cin
要服用?
回答by Miguel Carvajal
Yo have to do the following
你必须做以下事情
int temp;
vector<int> v;
while(cin>>temp){
v.push_back(temp);
}
also you can check for end of input using
您也可以使用检查输入结束
if(cin.eof()){
//end of input reached
}
回答by tabstop
If cin
is still interactive, then there's no notion of "no more input" because it will simply wait for the user to provide more input (unless the user has signaled EOF
with Ctrl+Dor Ctrl+Zas appropriate). If you want to process a line of data, then get a line from the user (with, say, getline
) and then deal with that input (by extracting out of a stringstream or similar).
如果cin
仍然是交互式的,那么就没有“不再输入”的概念,因为它只会等待用户提供更多输入(除非用户已适当地EOF
用Ctrl+D或Ctrl+Z表示)。如果您想处理一行数据,则从用户那里获取一行(例如,getline
),然后处理该输入(通过从字符串流或类似内容中提取出来)。
回答by 0x499602D2
It is very straightforward. All you need to do is perform the extraction as the condition:
这是非常简单的。您需要做的就是根据条件执行提取:
while (i < MAX_SIZE && std::cin >> x[i++])
while (i < MAX_SIZE && std::cin >> x[i++])
if the extraction fails for any reason (no more characters left, invalid input, etc.) the loop will terminate and the failure will be represented in the stream state of the input stream.
如果提取因任何原因失败(没有更多字符、无效输入等),循环将终止,并且失败将在输入流的流状态中表示。
Considering best practices, you shouldn't be using static C-arrays. You should be using the compile-time container std::array<T, N>
(or std::vector<T>
if the former is not supported).
考虑到最佳实践,您不应该使用静态 C 数组。您应该使用编译时容器std::array<T, N>
(或者std::vector<T>
如果前者不受支持)。
Here is an example using std::vector
. It also utilizes iterators which does away with having to explicitly create a copy of the input:
这是一个使用std::vector
. 它还利用迭代器,无需显式创建输入的副本:
std::vector<int> v{ std::istream_iterator<int>{std::cin}, std::istream_iterator<int>{}};
std::vector<int> v{ std::istream_iterator<int>{std::cin}, std::istream_iterator<int>{}};