I'm creating a calendar program and am trying to make it so that it will repeat the question if you don't enter a valid year, but if I don't enter a valid year, it repeats the message forever and won't let me input an answer. help would be appreciated.
#include <iostream>
#include "conio.h"
#include <string>
usingnamespace std;
int main(){
int year = 0
int validyear = 0
do {
cout << "What year is it?" << endl;
cin >> year;
} while (year <= 0)
if (year>0)
{validyear==1}
_getch();
}
I compiled your program and it ran fine. It repeated the question when I typed 0 or less, and went on when I typed 1 or more. You have some syntax errors here though.
1 2 3 4 5 6
int year = 0; //needed ";"
int validyear = 0; //same
} while (year <= 0); //needed ";"
validyear = 1; //needed ";" and == is a comparison operator. = is the assignment operator
He is probably using Visual Studio, I just tested with MSVC2010 and the code loops infinitely, but with GCC all "seems" to be working.
Tested on Windows 7 x86.
#include <iostream>
usingnamespace std;
int main () {
bool tochno = false;
int year=0;
int valid=0;
do {
cout<<"Enter year: ";
if(!(cin>>year))
{
cin.clear();
cin.ignore(cin.rdbuf()->in_avail());
}
if (year != 0)
tochno = true;
} while (year <= 0 );
valid ++;
cout<<"Valid years: "<<valid<<endl;
cin.ignore(cin.rdbuf()->in_avail()+1);
return 0;
}
This does the same thing as the original code, with the difference of not being buggy. Then again it may not do what you want to do, considering I have no idea what you tried to achieve.
But thing I was trying to do was stop you from entering b.c years or letters, I noticed when I typed in a word as the year it was converted to a negative number, so I was trying to tell it not to accept negative numbers, solving both problems.