Hopefully this will be a simple topic. I'm working on loops. I've found that loops work great as long as you don't enter a character when the loop expects an integer. For example, take this program:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
#include <iostream>
int main()
{
int num;
do
{
std::cout << "Enter 1 to quit, anything else to keep going: ";
std::cin >> num;
}while(num != 1);
return 0;
}
|
It works really well if I input any numbers-- if I input 1, the program ends, any other number-- even negative numbers-- and it keeps going. However, if I input f, when it asks me to enter a number, and I press Enter, the program enters into an infinite loop and I have to exit the program by clicking on the X on the program box. Why is that? I made another program without a loop to see what happens when I enter f when the program asks for an int:
1 2 3 4 5 6 7 8 9 10 11
|
#include <iostream>
int main()
{
std::cout << "Enter a number: ";
int num;
std::cin >> num;
std::cout << "You enter " << num << "!\n";
return 0;
}
|
I entered f here, and the output was:
Enter a number: f
-858993460
Press any key to continue . . .
Is that a random memory address? I went back to the loop I made and entered the value -858993460 when asked to enter a number, and it didn't cause any problems-- just treated it like any other number. Why does it cause an infinite loop if you enter a character in a loop that expects an integer? What validation code could you make to ensure the user is not able to enter a char when the loop asks for an int to avoid an infinite loop?
Also, I just made this program to see if entering a number when the program expects a character causes the same problem:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#include <iostream>
int main()
{
char letter;
do
{
std::cout << "Enter 'a' to quit, any other letter to keep going: ";
std::cin >> letter;
}while(letter != 'a');
//std::cout << letter << std::endl;
return 0;
}
|
But it doesn't! I can enter letters or numbers all day without a problem (no infinite loops). To validate an int, should you just accept a number into a char and convert it or something-- to avoid infinite loops?