Hi, I'm trying to write a simple program (or portion of a program), that will re-prompt a user for input each time the user enters invalid input, and then exit once the user has entered valid input. Here's what I have so far in main():
int main()
{
char input[SIZE];
cout << "Enter a string: ";
while (!InputString(i nput))
{
cout << "Invalid string entered. Try again: " << endl;
}
system("pause") ;
return 0;
}
And here's the body of the InputString() function:
bool InputString(cha r str[SIZE])
{
char ch;
int x = 0;
while ((ch = cin.get()) != '\n')
{
if (x != (SIZE - 1))
{
str[x++] = ch;
}
else
{
str[x] = '\0';
return false;
}
}
str[x] = '\0';
return true;
}
The odd thing that ends up happening is, "Invalid string entered. Try again: " is displayed three times, and then the program exits as if valid input was entered. Anyone know what's going wrong? Thanks.
int main()
{
char input[SIZE];
cout << "Enter a string: ";
while (!InputString(i nput))
{
cout << "Invalid string entered. Try again: " << endl;
}
system("pause") ;
return 0;
}
And here's the body of the InputString() function:
bool InputString(cha r str[SIZE])
{
char ch;
int x = 0;
while ((ch = cin.get()) != '\n')
{
if (x != (SIZE - 1))
{
str[x++] = ch;
}
else
{
str[x] = '\0';
return false;
}
}
str[x] = '\0';
return true;
}
The odd thing that ends up happening is, "Invalid string entered. Try again: " is displayed three times, and then the program exits as if valid input was entered. Anyone know what's going wrong? Thanks.
Comment