0

I am coding a very basic problem but I am stuck in reading input of an array in one row. I have used the technique used mentioned in How to user input the array elements in c++ in one line but I see that it doesn't work and it gives 'segmentation fault` in subsequent execution steps. I have included my code below.

#include<iostream>
#include<sstream>
#include <string>
#include<vector>
#include<algorithm>
using namespace std;

int main()
{
    int n,i,j,max=0,k,l;
    cin>>n;
    for(i=0;i<n;i++)
    {
       vector<int> v1;
       stringstream iss;
       string s;
       int value={0};
       max=0;
       getline(cin,s);
       iss<<s;
       while(iss>>value)
       {
          cout<<"Pushing values";
          v1.push_back(value);
       }
       //cout<<"After pushing";
       cout<<v1[0];
    }
    return 0;
}

It gives segmentation fault in the line cout<<v1[0];. Actually values aren't being pushed into the vector which can be checked simply uncommenting cout<<"After pushing"; and commenting cout<<v1[0];.

What is the problem here?

Actually my input looks like this:

4
1 3 4
1 10 100
21 88 17
23 34 45

Also I am wondering how to separate the nos after reading in a string if a space is existent between them?

Hamsa
  • 476
  • 5
  • 23

2 Answers2

3

Let's have a look at what your input looks like with explicit newlines:

4\n
1 3 4\n
1 10 100\n
21 88 17\n
23 34 45\n

After the cin >> n the remaining unread input will look like this:

\n
1 3 4\n
1 10 100\n
21 88 17\n
23 34 45\n

After the first getline it'll look like this:

1 3 4\n
1 10 100\n
21 88 17\n
23 34 45\n

See the issue? The first time you read a value from cin the line isn't completely read and the following getline reads the remainder of the line (which is an empty string). After that you try to read all the numbers in that line into the vector (no numbers are read because it's an empty string), and you try to read the first number in the vector (which will error because no numbers were added).

Slidy
  • 113
  • 7
2

std::cin remains \n after >> operator. You can simply use cin.get() to remove newline character.

fixed code:

#include<iostream>
#include<sstream>
#include <string>
#include<vector>
#include<algorithm>
using namespace std;

int main()
{
    int n,i,j,max=0,k,l;
    cin>>n;
    cin.get();
    for(i=0;i<n;i++)
    {
       vector<int> v1;
       stringstream iss;
       string s;
       int value={0};
       max=0;
       getline(cin,s);
       iss<<s;
       while(iss>>value)
       {
          cout<<"Pushing values";
          v1.push_back(value);
       }
       //cout<<"After pushing";
       cout<<v1[0];
    }
    return 0;
}

Reference:Why does cin command leaves a '\n' in the buffer?

openingnow
  • 134
  • 10