-2

in this code it is taking not taking input for i=0. It is taking input directly for i=1.

#include <bits/stdc++.h>

using namespace std;

int main()
{
    int n;
    cin>>n;
    vector<string> x;
    string q;

    for(int i=0;i<n;i++)
    {
        getline(cin,q);
        x.push_back(q);
        cout<<x.size();
    }

    for(int i=0;i<x.size();i++)
        cout<<x[i]<<endl;

    return 0;
}
JJJ
  • 32,902
  • 20
  • 89
  • 102
Stam
  • 3
  • 2
  • 1
    Could you explain a bit more what "not taking input" or "taking input directly" means? Show some example input and output, and what you expected to see instead. – JJJ May 20 '18 at 08:12
  • for i=0 it is directly printing x.size() it is not taking input for q. for ex-after i give input to n it directly prints x.size() not taking input to q – Stam May 20 '18 at 08:20

1 Answers1

0

Add an extra "getline(cin,q);" statement before "for loop" so that it reads the pending line where you entered input for "cin>>n;" statement.

Your new code will be:-

using namespace std;

int main()
{
   int n;
   cin>>n;
     vector<string> x;
 string q;
 getline(cin,q); // to read the pending line 
 for(int i=0;i<n;i++)
 {

   getline(cin,q);
    x.push_back(q);
    cout<<x.size();
 }
 for(int i=0;i<x.size();i++)
 cout<<x[i]<<endl;
    return 0;
}
Naveen
  • 56
  • 3
  • [`istream::ignore()`](http://en.cppreference.com/w/cpp/io/basic_istream/ignore) is a more explicit alternative, but pretty ugly in practice: `cin.ignore(std::numeric_limits::max(), '\n');`. For any practical use can be written as `cin.ignore(1<<30, '\n');` though. – Frax May 20 '18 at 08:31