Archived

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

Dethsythe

Newbie question...

Recommended Posts

Dethsythe    122
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 this post


Link to post
Share on other sites
Jo    122
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 this post


Link to post
Share on other sites
Lucasdg    122
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 ]=-

Share this post


Link to post
Share on other sites