2
#include <iostream>
using namespace std;


int main(int argc, char** argv) {

char text[200];
int input;


cin>>input;
if (input == 1)
{
    cin.getline(text, 200);
    cout<<text<<"\n";

}
else if(input == 0)
{
    cout <<"You entered a 0";
}

return 0;
}

I am trying to make a small program where the user gives an input either a 1 or 0. if the user enters a 1 then he can enter a whole sentence and stores it in the char array of text. My problem is that when I put the cin.getline() inside an if statement it no longer works. why is that?

Thanks

Bex
  • 51
  • 1
  • 2
  • 9

1 Answers1

2

It is not that cin.getline() doesn't work. It does exactly what has been asked of it: Read the line of text up to the next newline. It just so happens that cin >> input; has read some digits and then left the first non-digit input in the input buffer - which typically is a newline unless you typed something that wasn't a number.

You can work around this by calling cin.ignore(), which will "read everything up to the next newline and throw it away".

Ideally, you should decide whether you want to use cin >> or cin.getline(), and use one or the other, but that means then reading a string of text and in your code converting to a digit, and if you are a novice, that's probably a bit more complex than you actually want to make it.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227