简体   繁体   中英

Is it possible to read Full name using 1 string Variable in C file management?

This C program is Ok if single word name is used. Actually I tried to make a text file reader that can store data in structure variable. And after that i will sum how many day they attended. But I am facing a issue when I use full name. My code is given below.

#include<stdio.h>

struct student
{
    int serial;
    int roll;
    char name[210];
    int day1,day2;
};

main()
{
    struct student read;
    FILE *fp2;

    fp2 = fopen("student_file.txt","r");
    if(fp2==NULL)
      printf("Not find");
    while(fscanf(fp2,"%d. %d %s %d %d",&read.serial,&read.roll,read.name,&read.day1,&read.day2)==5)
    {
      fprintf(stdout,"%d %d %s %d %d\n",read.serial,read.roll,read.name,read.day1,read.day2);
    }
    fclose(fp2);
}

This txt file can read easily.

1. 123 Nahid 1 1
2. 465 Zahid 1 0
3. 789 Sahid 1 1
4. 159 Mahid 1 0

But I want to read a text file using fscanf and fprintf.

5. 889 Mark Joe 1 0
6. 669 M. J. Rakib 1 0

Is it possible to read full name using file management in c? It will helpful to me if I can read only 1 line at least.

Yes this is possible supposing a name cannot contains digits (personalty I never see a name having) just modify the fscanf format to use:

"%d. %d %209[^0-9] %d %d"

209 is here to not take the risk to write out of the array in case the name is too long

because extra spaces are saved at the end of the name you need to remove them, as you can see if I print with that format:

"%d %d '%s' %d %d\n"

producing

1 123 'Nahid ' 1 1
2 465 'Zahid ' 1 0
3 789 'Sahid ' 1 1
4 159 'Mahid ' 1 0
5 889 'Mark Joe ' 1 0
6 669 'M. J. Rakib ' 1 0

Warning in your code if you cannot open the file you will execute the while so you call fscanf then fclose on NULL with an undefined behavior

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM