Skip to content

C++ Help....

Featured Replies

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

 

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.

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

Create an account or sign in to comment

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.