Jump to content

Recommended Posts

Posted

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..

 

Posted

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.

Posted

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;
}

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.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...