for loop not working correctly (runs 1 less time than it should?)

My for loop collects user input one less time than I want it to and I have no idea why? The first time it outputs the statement "Enter strings", there's no input and it seems to completely ignore the rest of the code and just skips to the next loop. It works perfectly fine after the first loop. Any help would be appreciated. Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  int main(){
int rows, length;
string input;


cout<<"Enter number of rows: ";
cin>>rows;

for(int i=0;i<rows;i++){
    cout<<"Enter strings: ";
    getline(cin, input);
    length=input.length();
  for(int j=0;j<length-1;j++){
       cout<<length;
      }
}
You can try:
1
2
cin>> rows;
cin.ignore(); // cin.get() works also 


I'm not sure what's the point of your second for loop though.
Last edited on
Oh its for a homework assignment. If i may, what does cin.ignore or cin.get() do?
Last edited on
It basically clears the std::cin buffer so any data left from the first integer get (the return key), leaving it clear for the getline.
Thank you so much! It worked! Just out of curiosity, can you tell me why my code didn't work originally?
Topic archived. No new replies allowed.