Αντώνης 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.. Quote
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. Quote
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; } Quote
Αντώνης Posted March 18, 2011 Author Posted March 18, 2011 No, length dont work in INT ... anyway ty Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.