Click here to Skip to main content
15,891,708 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have no idea how to extract year from IC number under convertYearofBirth and convert it from string to int.
Example IC : 190508143749 where '19' refers year, '05' refers month, '08' refers DOB.

What I have tried:

C++
#include <iomanip>
#include <string>
#include <cstring>
using namespace std;

bool checkCharacter(string);
int convertYearofBirth(string);
void checkEligibility(string, int);

int main()
{
	string name, IC;
	int cont = 1, year;

	do
	{
		cout << "Name: ";
		getline(cin, name);
		cout << "IC No (without hypen): ";
		cin >> IC;

		if (checkCharacter(IC))
		{
			year = convertYearofBirth(IC);

			checkEligibility(name, year);

		}
		else
			cout << "Please key in the correct IC no!" << endl;

		cout << "Cont (1-yes, 2-no)?";
		cin >> cont;
		cin.ignore();
		cout << fixed << setprecision(2) << endl;

	} while (cont == 1);

	return 0;
}

bool checkCharacter(string IC)
{
	for (int i = 0; i < IC.length(); i++)
		if (isdigit(IC[i]) == false)
			return false;
	return true;
}

int convertYearofBirth(string IC)
{
	for (int i = 0; i < 10; i++)
	{
		IC = stoi(IC.substr(0, 1));

	} 
}

void checkEligibility(string name, int year)
{
	if (year <= 2021)
	{
		cout << name << " is " << year << " years old." << endl;
		cout << name << " is eligible to vote! " << endl;
	}
	else
	{
		cout << name << " still has " << year << " to reach 21 years old." << endl;
		cout << name << " is not eligible to vote! " << endl;
	}
}
Posted
Updated 7-May-22 14:22pm
v2
Comments
Richard MacCutchan 8-May-22 4:11am    
If you know that the first six digits ar the year, month and day, then it is a simple matter to extract each pair of digits and convert them to integers.

Here is one simple and primitive way.
C++
void TestDayString()
{
	std::string IC( "190508143749" );

	char yearStr[ 4 ] = { 0 };
	char monthStr[ 4 ] = { 0 };
	char dayStr[ 4 ] = { 0 };

	strncpy( yearStr,  & IC[0], 2 );
	strncpy( monthStr, & IC[2], 2 );
	strncpy( dayStr,   & IC[4], 2 );

	int year = atoi( yearStr );
	int month = atoi( monthStr );
	int day = atoi( dayStr );

	printf( "year, month, days are %02d %02d %02d\n", year, month, day );
}
as an added bonus, I tried it and it works.
 
Share this answer
 
Comments
merano99 7-May-22 20:24pm    
Since the solution works, you get my 5, but I would prefer a pure C++ solution.
The function to find a year is broken. It might look like this.
C++
int convertYearofBirth(const std::string &IC)
{
	int x;
	// x = stoi(IC.substr(0, 2));
	std::istringstream(IC.substr(0, 2)) >> x; 
	return x;
}

The other functions work exactly according to the same scheme.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900