繁体   English   中英

读取以空格分隔的输入数字并保存到数组中

[英]Read input numbers separated by space and save into an array

我必须编写一个程序,从键盘读取一行数字并将它们保存到一个数组中,数字必须写在一行中,我写了这个,但由于无限循环而不起作用,有什么建议吗?

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
--这必须是向量
-- 向量.v[0] = 2
-- 向量.v[1] = 43
-- 向量.v[2] = 65
-- 向量.v[3] = 56

如果您知道必须阅读多少个数字,则有一种更简单的方法:

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

通过修改它可以工作。

int main() {

    int numCasos = 0, contNumCasos = 0, numElem = 0;
    string aux;
    cout << "Numero de casos: " << endl;
    cin >> numCasos;
    while (contNumCasos < numCasos) {

        cout << "Numero de elementos: " << endl;
        cin >> numElem;
        cout << "Ingrese los elementos separados por espacios: " << endl;
        cin.ignore();
        vector.cont = 0;
        getline(cin, aux);
        istringstream iss(aux);
        for (int i = 0;i < numElem;i++) {
            iss >> aux;
            vector.v[i] = stoi(aux);
            vector.cont++;
        }
        cout << sumaBuenos(vector) << endl;
        contNumCasos++;
    }

    system("pause");
    return 0;
}

给有同样问题的人。

#include<iostream>
using namespace std; 

int main() 
{   
    int n;
    cout << "input numbers" << endl;
    cin >> n; 

    vector<int> v(n);

    for ( int i=0; i<n; ++i )
    {

        cin >>v[i];

    } 
    return 0; 

} 
#include <bits/stdc++.h> 
#include<iostream>

using namespace std; 
  
int main() 
{
    int sizeofarray;
    cin >> sizeofarray;
    int a[sizeofarray];
    int i;

for (i = 0; i < sizeofarray; ++i)
{
    cin >> a[i];
}
    return 0; 
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM