Search code examples
c++vectorstdvectorstringstreampush-back

Issues related to user input array elements in one line in c++


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?


Solution

  • 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?