• ### Popular Now

• 12
• 12
• 9
• 10
• 13

#### Archived

This topic is now archived and is closed to further replies.

# Newbie question...

This topic is 6375 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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...

##### Share on other sites
That code is completely useless! That is your first bug

Maketty
(Matthew FitzGerald)
Knightvision Games

##### Share on other sites
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.

##### Share on other sites
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 buffercin >> 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 ]=-