-
cin.getline
I'm having a problem with prompting and getting user input. Below is my code
Code:
sendRegisterSymbol()
{
char tmp[256];
CSIString domain;
CSIString mfile;
CSIString instance;
CSIString symbol;
std::cout << "Enter a domain name:\n";
std::cin.getline(tmp, sizeof(tmp));
domain.assign(tmp);
std::cout << "Enter an mfile name:\n";
std::cin.getline(tmp, sizeof(tmp));
mfile.assign(tmp);
std::cout << "Enter an mfile instance:\n";
std::cin.getline(tmp, sizeof(tmp));
instance.assign(tmp);
std::cout << "Enter a symbol:\n";
std::cin.getline(tmp, sizeof(tmp));
symbol.assign(tmp);
.
.
.
The problem here is that first time this code is encountered, the first piece(everything dealing with domain is sort of passed by. For instance, when I run the program, the user gets prompted as follows:
>Enter a domain name: Enter an mfile name:
The user doesn't get the option to enter the domain.
Every subsequent time that sendRegisterSymbol() is called, everything works as I want it to:
>Enter a domain name:
Its only the first time I enter the function that I get the bad output.
I tried adding cin.ignore prior to the code dealing with domain. That fixes it the first time through, but then every subsequent time I call sendRegisterSymbol, I have to hit enter twice to get to where I want to.
Any ideas???? Thanks in advance!
Please use [code][/code]Tags
-
so would it make sense to do a fflush(stdin); as soon as the sendRegisterSymbol() method is called? I would think so, but it doesn't seem to be helping.
-
You cant call fflush on stdin. You can only flush output streams like that never input streams.
-
It is never ok to flush stdin: http://faq.cprogramming.com/cgi-bin/...&id=1043284351
Your only solution is to place the summy getline() before your getline() sequence, as Salem explained.
And you might want to place a return type on that function. Defualting to int is no longer allowed.
-
disregard the fflush solution. I did a work around:
code:
__________________________________________
sendRegisterSymbol()
{
char tmp[256];
static bool firstTime=true;
CSIString domain;
CSIString mfile;
CSIString instance;
CSIString symbol;
if(firstTime)
{
cin.ignore(1, '\n');
firstTime=false;
}
std::cout << "Enter a domain name:\n";
std::cin.getline(tmp, sizeof(tmp));
domain.assign(tmp);
std::cout << "Enter an mfile name:\n";
std::cin.getline(tmp, sizeof(tmp));
mfile.assign(tmp);
std::cout << "Enter an mfile instance:\n";
std::cin.getline(tmp, sizeof(tmp));
instance.assign(tmp);
std::cout << "Enter a symbol:\n";
std::cin.getline(tmp, sizeof(tmp));
symbol.assign(tmp); .
.
.
_____________________________________________
static bool firstTime=true;
if(firstTime)
{
cin.ignore(1, '\n');
firstTime=false;
}