Search code examples
c++getline

Reading a row until newline in the console


I need to make a program that reads n numbers in a row. For example, the user first puts in a list of 2 numbers like this:

P n

I managed to read those with scanf but now I need to read the n following numbers, these numbers are given in a row as follows.

1 6 3 99 ... n times These numbers must be read all at once (or give the impression of).

I already tried using

while(getline(cin,str)){
// do something with str
} 

As explained in this thread but I need the actions inside the while loop to stop when I hit the intro key. With my current implementation they don't stop, it just keeps waiting for more lines to read.

In summary: First, user must be able to input two numbers (P and n)(done!) then hit enter and start typing a list of n numbers (not done!).

Here is my code.

#include <iostream>
#include <string>
#include <sstream>

using namespace std;
int main(void){
    int P,n;
    scanf("%d %d",&P,&n);
    string val;
    int score[P];
    int i;
    for(i=0;i<P;i++){
        score[i]=0;
    }
    while(getline(cin,val)){
        printf("Val=%s\n",val.c_str());
        stringstream stream(val);
        int local;
        while(stream >> local){
            score[local]=score[local]+1;
            printf("%d-%d\n",local,score[local]);
        }

    }
    for(i=0;i<P;i++){
        printf("%d-%d\n",i,score[i]);
    }
    return 0;
}

Solution

  • Use scanf() inside the n times loop instead of getline().

    for(int i = 0; i < n; i ++){
       scanf("%d",&variable);
    }