阅读用空格隔开输入数字,并保存到一个数组 [英] Read input numbers separated by space and save into an array

查看:619
本文介绍了阅读用空格隔开输入数字,并保存到一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须写一个程序,从键盘读取一个行号,并把它们保存到一个数组,数字必须在一行刚刚写,我写的,因为无限循环的这一点,但不`吨的工作,任何建议?

i have to write a program which read from the keyboard a line of numbers and save them into an array, numbers have to be written just in a line, i wrote this but doesn`t work because of an infinite loop, any suggestion?

int main() {

    int numCasos = 0, contNumCasos = 0, numElem = 0;
    string aux;
    cout << "Number of cases: " << endl;
    cin >> numCasos;
    while (contNumCasos < numCasos) {

        cout << "Number of elements: " << endl;
        cin >> numElem;
        cout << "Enter the Elements separated by space: " << endl;
        cin.ignore();
        vector.cont = 0;
        int i = 0;
        while ((vector.cont < numElem) && getline(cin,aux,' ')){
            vector.v[i] = stoi(aux);
            vector.cont++;
            i++;
        }
    }

    cout << sumaBuenos(vector) << endl;
    cin.ignore();
    system("pause");
    return 0;
}

一个例子:结果
控制台:元素的数量:结果
用户:4结果
控制台:输入空格分隔的元素:结果
用户:2 43 65 56结果
- 这有可能成为矢量搜索
- vector.v [0] = 2搜索
- vector.v [1] = 43结果
- vector.v [2] = 65结果
- vector.v [3] = 56结果

An example:
console: Number of elements:
user: 4
console: Enter the Elements separated by space:
user: 2 43 65 56
--this has to be the vector
-- vector.v[0] = 2
-- vector.v[1] = 43
-- vector.v[2] = 65
-- vector.v[3] = 56

推荐答案

如果你知道你有多少个号码读有一个简单的方法:

if you know how many numbers you have to read there is a simpler way:

int n;
cin>>n; // how many numbers;
vector<int> v(n);
for ( int i=0; i<n; ++i ){
    cin>>v[i];
}

这篇关于阅读用空格隔开输入数字,并保存到一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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