parmigiano
parmigiano

Reputation: 105

C strcpy and strcat

I have a question about strcpy and strcat.

In the program I'm trying to make I need to get the year someone was born from a fiscal code. The fiscal code is given as a char from a serial port,

strcpy(temp, code[6]);
strcat(temp, code[7]);
yyyy = 1900 + (atoi(temp));

This is what I came up with: basically the last two digits of the year will be added to 1900 (I know it doesn't quite work with people born in the 2000). The first digit is copied from the full code to a temp variable using strcpy, then I would like to add the second digit to then use atoi and convert eveything to integer; for that I use strcat in a way I've never seen before. Am I doing it right?

Upvotes: 1

Views: 868

Answers (1)

Paul R
Paul R

Reputation: 212979

No need for strcpy/strcat (and they are not appropriate in this context anyway). No need for a temporary string either. You can just do this:

yyyy = 1900 + (code[6] - '0') * 10 + (code[7] - '0');

This just extracts the two digit characters, converts each one to an integer in the range 0..9, and then calculates the year from these two values.

Upvotes: 5

Related Questions