如何从控制台读取空格分隔的数字? [英] How to read space separated numbers from console?
问题描述
向量< int>
,但我没有得到如何做到这一点。 这是我到目前为止所做的:
int n = 0;
)断开
vector< int>脚步;
while(cin>> n)
{
steps.push_back(n);但是,这需要用户按一个无效的字符(例如<$),而不是一个无效的字符(例如<$ p
$ b < c $ c> a,而
循环。我不想要。
只要用户输入
0 2 3 4 5
,然后按/ code>我想要循环被打破。我尝试使用
istream_iterator
和cin.getline
也,但我不能得到它的工作。
我不知道用户将输入多少个元素,因此我使用
向量
。
请建议正确的方法。
解决方案
getline
结合istringstream
来提取数字。std :: string input;
getline(cin,input);
std :: istringstream iss(input);
int temp;
while(iss>> temp)
{
yourvector.push_back(temp);
}
I'm trying to do a simple task of reading space separated numbers from console into a
vector<int>
, but I'm not getting how to do this properly.This is what I have done till now:
int n = 0; vector<int> steps; while(cin>>n) { steps.push_back(n); }
However, this requires the user to press an invalid character (such as
a
) to break thewhile
loop. I don't want it.As soon as user enters numbers like
0 2 3 4 5
and pressesEnter
I want the loop to be broken. I tried usingistream_iterator
andcin.getline
also, but I couldn't get it working.I don't know how many elements user will enter, hence I'm using
vector
.Please suggest the correct way to do this.
解决方案Use a
getline
combined with anistringstream
to extract the numbers.std::string input; getline(cin, input); std::istringstream iss(input); int temp; while(iss >> temp) { yourvector.push_back(temp); }
这篇关于如何从控制台读取空格分隔的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!