简体   繁体   中英

Read input numbers separated by space and save into an array

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;
}

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];
}

With a modification it works.

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;
}

to someone who have the same problem.

#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; 
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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