Newbie question...

Started by
2 comments, last by Dethsythe 23 years, 6 months ago
Simple question (probably difficult answer, heh) #include void main() { int x = 0; while(x == 0) { cout << "Enter a number"; cin >> x; switch(x) { case 1:{ cout << x; break; } case 2:{ cout << x; break; } case 3:{ cout << x; break; } default: { x = 0; } } x = 0; } } if the user enters a number it''s cool, if the user enters a letter it goes nuts! is that a bug /w MSVC or what? thanks in advance...
Dethsythe
Advertisement
That code is completely useless! That is your first bug


Maketty
(Matthew FitzGerald)
Knightvision Games

Maketty (Matthew FitzGerald) The meaning of Life part 5:Live organ transplants...
Your program is expecting a certain data type here, but it''s getting another without any error checking. Back when I was in school doing this crap it was generally advised to use some sort of buffer to get your information and then check it for validity and all that good stuff.

For example is you had read it in as a string (your buffer) then you could read both letters, numbers, end of line characters, etc, and then done some data checks to make sure everything won''t come crashing down and to let the user know they made a mistake.
-----------------------------Mice are an excellent source of mice.
An error sequence a day keeps the agony away.

#include

void main()
{
int x = 0;

while(x == 0)
{
cout << "Enter a number";
cin.clear(); //clears the buffer
cin >> x;


if (!cin || cin.bad()) //checks if data type is not good
{
cin.clear(); //clears the buffer
x = 0; //resets to 0
}

switch(x)
{
case 1:{ cout << x; break; }
case 2:{ cout << x; break; }
case 3:{ cout << x; break; }
default: { x = 0; }
}

x = 0;
}
}



By clearing the buffer, and resetting x to 0 again, your program won''t screw up because if anything but an int is entered, it will reset x to 0.

Good luck!




-=[ Lucas ]=-
-=[ Lucas ]=-

This topic is closed to new replies.

Advertisement