如何从控制台读取空格分隔的数字? [英] How to read space separated numbers from console?

查看:602
本文介绍了如何从控制台读取空格分隔的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个简单的任务从控制台读取空格分隔的数字到向量< 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 the while loop. I don't want it.

As soon as user enters numbers like 0 2 3 4 5 and presses Enter I want the loop to be broken. I tried using istream_iterator and cin.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 an istringstream to extract the numbers.

std::string input;
getline(cin, input);
std::istringstream iss(input);
int temp;
while(iss >> temp)
{
   yourvector.push_back(temp);
}

这篇关于如何从控制台读取空格分隔的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆