"Michele 'xjp'" <michele@removethis.nectarine.it> wrote in message
news:469fc597$0$36452$4fafbaef@reader5.news.tin.it...
Hi there.
http://rafb.net/p/GhK3AU65.html
[Code from link inserted]
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
#define clrscr() printf("\e[2J")
int main(void) {
bool end = false;
char scelta;
do
{
clrscr();
cout << "*******************************************" << endl
<< "************ foo **********" << endl
<< "*******************************************" << endl <<
endl
<< "6 - bar" << endl
<< "0 - exit" << endl;
cin >> scelta;
switch (scelta)
{
case '6': {
cout << "type here:";
string titolo;
getline(std::cin, titolo, '\n');
Add this line to help you determine what's going on a little bit:
std::cout << titolo;
break;
}
case '0':
end = true;
exit(0);
}
}
while (!end);
return 0;
}
If you press '6', and 'enter', it will have to ask for another insert of
a string. However, in this case, it goes straight without waiting for
input... any ideas?
What is happening, is the std::cin >> scelta; will look for a character,
but
the input doesn't get processed until you press enter. So you press 6 and
press enter. What is waiting then in std::cin is "6\n". The cin >>
scelta;
grabs the character 6, but leaves the carriage return. getline( std::cin
, titolo, '\n'); is processed and, hey, the '\n' is already there, so
that's
what it loads into titolo, nothing. That si what the std::cout << titolo;
will show. Instead of pressing 6 then enter, try "6 This is some input"
and press enter, and you'll see that " This is some input" is displayed.
So what you want to do is ignore eveyrthing in cin after you read your
character.
std::cin.ignore( 999, '\n' );
after the cin >> scelta;
would do the trick. I'm sure there's a better number to use than 999
(maybe a constant?) but I'm not sure what it is. Maybe someone else can
say.
std::numeric_limits<std::streamsize>::max() is the magic number. Ignore()
sentinel (here '\n').