fitdream
fitdream

Reputation: 13

How to read sequences with spaces and stop when the user presses "enter" in C++?

As title, I am a beginner in learning C++.

I want to read several sequences(s1,s2,s3...) containing integers seperated by spaces into an array,and stop reading s1 to read s2 by pressing "enter".

#

Here's the test data:

4 9 6 6

1 2 3 4

3 3 5 6 9 15 18 15 18 30 3 3 5 6 9 15 18 15 18 30 1 9 9 25 36

The result I expect would be :

arr[0]={4,9,6,6}

arr[1]={1,2,3,4}

arr[2]={3,3,5,6,9,15,18,15,18,30,3,3,5,6,9,15,18,15,18,30,1,9,9,25,36}

#

I used a time consuming way to read data into my array:

    while(1){
    int i=0,j=0;
    int arr[100][25];
    char test;
    while(1){
    stringstream ss;
    cin.get(test);
    if(test==' '){
        ss<<seq;
        seq.clear();
        ss>>arr[i][j];
        j++;
        continue;
    }
    else if(test=='\n'){
        ss<<seq;
        seq.clear();
        ss>>arr[i][j];
        i++;
        j=0;
        break;
    }
    else{
        seq=seq+test;
        }
      }
    }

Online Judge will show "TLE" when the program reads big integers.

I know that break down integers into characters is a time consuming work,

what can I do with my program?

Upvotes: 1

Views: 53

Answers (1)

GoodDeeds
GoodDeeds

Reputation: 8527

One way to do this could be using strings. The example below, based on this answer, reads each line in a string, and splits it by space. It will work only if the numbers are split by single spaces. The split numbers are stored in a vector of strings in the example, and can be converted to int using stoi.

string nums;
while(getline(cin,nums)) {
    istringstream iss(nums);
    vector<string> tokens;
    copy(istream_iterator<string>(iss),
         istream_iterator<string>(),
         back_inserter(tokens));
    // print what is added
    for(int i = 0; i < tokens.size(); i++) {
        cout << tokens[i] << " ";
    }
    cout << endl;
}

Upvotes: 1

Related Questions