When data is read from a text file with fscanf, data from the next column is appended to the string data. How can I get only the data from that column?
Input file: student.txt
Donald 23 KOR CE
Mitchell 24 USA EE
John 22 KOR CE
Output:
Donald 23 KORCE CE
Mitchell 24 USAEE EE
John 22 KORCE CE
In the data in the first row, the country should be KOR, but it comes out as KORCE.
My code so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LENGTH 100
typedef struct
{
char name[20];
int age;
char country[3];
char dept[2];
} STUDENT;
int main()
{
int i = 0;
STUDENT student[15];
// Initialize the student array
for (i = 0; i < 15; i++) {
memset(student[i].name, 0, sizeof(student[i].name));
student[i].age = 0;
memset(student[i].country, 0, sizeof(student[i].country));
memset(student[i].dept, 0, sizeof(student[i].dept));
}
// Open the file for reading
FILE *fp = fopen("student.txt", "r");
if (fp == NULL)
{
puts("Error: Could not open file 'student.txt'");
return 1;
}
// Read the file line by line
char line[MAX_LINE_LENGTH];
while (fgets(line, MAX_LINE_LENGTH, fp) != NULL) {
// Parse the line and fill the structure
if (sscanf(line, "%s %d %s %s\n", student[i].name, &student[i].age, student[i].country, student[i].dept) != 4) {
printf("Error: Invalid data in file 'student.txt'\n");
return 1;
}
// Print the structure
printf("Name: %s\n", student[i].name);
printf("Age: %d\n", student[i].age);
printf("Country: %s\n", student[i].country);
printf("Dept: %s\n", student[i].dept);
i++;
}
// Close the file
fclose(fp);
return 0;
}
I want the country name to read normally as 3 characters.