Codechef IDE getline input empty

Hi! Please help, I’m using a getline(cin, str) in a for loop to get string inputs but the problem is, on the first run of the for loop, the getline is somehow empty and the first input somehow only appears in the second iteration of the for loop.
For example, the code:
for(int i = 0; i < 4; i++){
string str = "";
getline(cin,str);
cout<<str;
}

If the input is,
Hello
Bye
Good
Haha

Then for some reason the first iteration is empty on codechef IDE and the second iteration outputs Hello till Good.
How can I fix it? Is the codechef IDE broken or is my code broken?

Is there any fix? Thanks in advance

I think the code you shared is incomplete, and I 'm pretty sure that in the original code you would’ve used a cin before this loop so from available info, I can guess that the original code might have looked something like this

#include<bits/stdc++.h>
using namespace std ;
int main(){
  int n ; 
  cin >>n  ; // NOTE THAT THIS CIN IS SCREWING UP THE CODE 
  for(int i = 0; i < 4; i++){
    string str = "";
    getline(cin,str);
    cout<<str;
  }
}

So actually using this cin before the getline() won’t be clearing up the buffer and the ‘\n’ i.e. the endline after cin would be counted as an input string (with size zero of course). So in order to fix this we will take an input character (’\n’ in this case)after cin so as to clear up the buffer by adding a getchar() after cin. So the final code would like.

#include<bits/stdc++.h>
using namespace std ;
int main(){
  int n ; 
  cin >>n  ;
  getchar() ;  //ADD THIS AFTER USING CIN (BEFORE getline())
  for(int i = 0; i < 4; i++){
    string str = "";
    getline(cin,str);
    cout<<str;
  }
}

PS: IDE is not broken

4 Likes

Thank you! This seems to have fixed the problem :smiley: