0

i have a problem with input char to my program

#include <iostream>
using namespace std;

int  main()
{
int choise;
char word[81];


cin >> choise;
cout << "enter the word:" << endl;
cin.getline(word, 81);

return 0;
}

the visual studio open the input to "choise" but skip on cin.getline (it the same if i replace it with gets_s).

i tried to write cin.get(); before the "getline"... but then the program not get's the first char (if i put 'aa' it get 'a') what can i do? thanks

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
dani1999
  • 89
  • 2
  • 10

2 Answers2

1

Its because you entered a newline for the program to accept the integer you entered for choice, the that newline is not extracted from the buffer, leaving it to be read in your next input operation. The getline call reads that left-over newline, and is happy with that.

There are a couple of ways to solve your problem. The first and most obvious is to use std::string for the word variable, and then use the normal input operator >> as that will skip leading whitespace (which includes newline).

Another solution is to tell the input stream to ignore until and including a newline. The linked reference has an example on how to do exactly that.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

After entering the integer you press enter, and this enter input is left in the buffer area and used as the next input for getline and the computer assumes you're done. add this line before getline statement and re- compile it. cin.ignore().

Samuel
  • 612
  • 2
  • 9
  • 25
  • ohhhi put cin.ignore(); and now it ok but tell me. why when i put cin.get(); before the "getline" then the program not get's the first char (if i put 'aa' it get 'a') – dani1999 Jan 26 '15 at 11:11
  • i do not understand exactly what you mean there because when i add the `cin.get();` statement, the program does not exhibit those behaviors you're saying. explain more or ask another question. – Samuel Jan 26 '15 at 12:42