#include <iostream>
usingnamespace std;
int c = 1;
int a = 0;
int main (void)
{
do
{
cout << "Number:"<< a++ << endl;
cout << "Type 1 to learn how to count to the next number, or punch in 2 to stop the program:" << endl;
cin >> c;
if(c < 1 && c < 2 || c!=1 && c!=2)
{
cout << "You are not ready for this program." << endl;
return 0;
}
elseif (c == 2)
{
break;
}
}
while (c == 1);
if(c==2)
{
cout << "Meh...." << endl;
}
return 0;
}
When my friend enters 'k', it disrupts the whole program (repeats itself over and over again), while when I enter 'k' it goes and quits the program instead of repeating itself over and over. Does anyone know why this is happening?
You may want to take a look at http://www.functionx.com/cpp/Lesson18.htm
This site introduces you to exception handling, which would certainly be beneficial in this situation. If I were to run this myself, i'd use stringstream to assure that only numbers are entered, when using stringstream it's exactly the same as using cin/cout, except you are messing with strings instead of the console. If you do something like this:
1 2 3 4 5 6 7 8 9 10 11 12
int getintinput(int& intval){
string str;
getline(cin,str);
stringstream ss;
ss << in;
ss >> intval;
if (!ss.fail())
return 1;
return 0;
}
You'll be assured that only an intvalue is placed into the variable, if the function returns 0, the user failed, otherwise they got it working.
Seems like your compiler is newer than your friend's.
In C++03, failed integer input does not alter the int variable (so it remains 1, and since you do not check cin's error state, the loop runs endlessly)
In C++11, failed integer input writes the value 0 to the int variable (so your if clause exits the program)
(for references, C++03 22.2.2.1.2[lib.facet.num.get.virtuals]/11 and C++11 ยง 22.4.2.1.2[facet.num.get.virtuals]/3)