Sam Keith
Sam Keith

Reputation: 99

Concatenate parts of names separated by comma saved in text file in C

I've a .txt file with names of employees. Each line ends with a newline.
I need to concatenate the first 3 characters of the first name and the last name to form one name, e.g.,

Schmit,Eric

should give the output

EriSch.

There are about 50 lines of names. How can I use fgets() or getchar() to do this along with

FILE *file = fopen ( "FileName.txt", "r" );

I also have a function

void ConcatName(char* firstname,char* lastname,char buffer[])

that stores the first three characters of firstname and lastname in buffer and prints it out.

Upvotes: 1

Views: 57

Answers (1)

PeCosta
PeCosta

Reputation: 537

You can use strtok() to divide into two strings. So for a given employee you should do

char* token = strtok(EmployeeName, ','); 
strcpy(SurName, token);
token = strtok(NULL, delim);
strcpy(FirstName, token);

After you just need to use concatenate the first 3 characters each name:

strncat(FinalName,FistName,3);
strncat(FinalName,SurName,3);

Just make sure to propperly initialize FirstName,SurName and FinalName and put the code inside a loop that reads each line one by one:

   while ((read = getline(&EmployeeName, &len, fp)) != -1) {'code'}

Upvotes: 2

Related Questions