Αντώνης Posted March 17, 2011 Posted March 17, 2011 Here is my code... #include <iostream> using namespace std; void main() { int year; cout << "Please give a year " << endl; cin >> year; cout << "\n You Entered: " << year; } Well... that i want is the length of year max 4 numbers, anyone can help me? I dont want this way.. if (year > 9999) { //Code } im new in c++, i try year.length(); ... but dont work.... and visual studio dont help in code syntact... i mean dont show you what must do like c# or simple vb project.... Soz for my bad english..
Hax0r Posted March 17, 2011 Posted March 17, 2011 if(year.length()!=4) { cout <<"Wrong year value"<< endl; } else { cout <<"Correct...(4 digits)"<< endl; } I'm not sure if it works on integers...but you can set year as string.
Hax0r Posted March 17, 2011 Posted March 17, 2011 Alright. this program gets strYear. if strYear is max 4 digits it checks if it really is a number.If it is a number it converts it to integer in intYear. +outputs messages #include <iostream> #include <sstream> using namespace std; int main() { int intYear; string strYear; cout <<"Value for strYear:"; cin >> strYear; if(strYear.length()<=4) { stringstream sti(strYear); sti >> intYear; //this should be two lines lower but there's a problem with the if...nvm it works like this too if(intYear==0) { cout<<"Wrong year input...use numbers!"; } else { cout<<"strYear is <= 4 digits, converting it to integer in variable intYear..."<<endl; } } else { cout<<"Wrong year input.(must be < 9999)"<<endl; } return 0; } or hell of easier: #include <iostream> using namespace std; int main() { int year; cin << year; if((year>0)&&(year<9999)) { //code } else { cout<<"Wrong year!"; } return 0; }
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now