-1
#include<vector>
#include<iostream>
using namespace std;

int main(){
    int number;
    cin>>number;
    string s1;
    vector<string> lists;
    for(int i=0;i<number;i++){
        getline(cin,s1);
        lists.push_back(s1);
    }
    for(int i=0;i<number;i++)
        cout<<lists[i]<<" ";    
}

When I enter 5 (for eg.) as input number, I am only able to enter 4 strings instead of 5. Can anyone help me out?

Thank you.

Christian Hackl
  • 27,051
  • 3
  • 32
  • 62

2 Answers2

0

after the line cin>>number; there is still the newline character \n (because you pressed enter to input the value )in the input buffer, to fix this you add a line with cin.ignore();

int main(){
    int number;
    cin>>number;
    cin.ignore();  // add this line
    string s1;
    vector<string> lists;
    for(int i=0;i<number;i++){
        getline(cin,s1);
        lists.push_back(s1);
    }
    for(int i=0;i<number;i++)
        cout<<lists[i]<<" ";    
}
suvojit_007
  • 1,690
  • 2
  • 17
  • 23
0

You are mixing line-based input (getline) and non-line-based input (cin>>number). This causes your first getline call to read an empty string into s1, because the \n in the stream has not yet been consumed.

So lists actually has 5 elements at the end, it's just that your output makes it hard to notice.

In order to prevent the problem, convert everything to line-based input instead. Replace this:

int number;
cin>>number;

With this:

std::string line;
std::getline(std::cin, line);
auto const number = std::stoi(line);

This is a superior solution anyway, because it makes it easier to detect wrong input (when the user enters something other than an integer number for number).

Christian Hackl
  • 27,051
  • 3
  • 32
  • 62