简体   繁体   中英

get the values for each line in the file in c

I need to read this main.txt file:

STUDENT ID 126345
TEACHER MATH CLASS 122

And i need to get each values from this file . If this main.txt file was like this:

STUDENT ID 126345
TEACHER ID 3654432

I could do it like this:

#include <stdio.h>

int main(){
    FILE *ptr_file;

    int id;
    char string1[100],string2[100];
    ptr_file = fopen("main.txt","r");

    while(fscanf(ptr_file,"%s %s %d",string1,string2,id) != EOF){
       }
    }

But I can't use fscanf() function because space amount between these values is not equal for each line. How can i get every value in line by line like this code ?

If every line has 3 values separated by empty spaces (or tabs), then

fscanf(ptr_file,"%s %s %d",string1,string2,&id);

is OK (and note that I used &id instead of id ), because %s matches a sequence of non-white-space characters, so it doesn't matter how many empty spaces are between the values, %s will consume the empty spaces:

#include <stdio.h>

int main(void)
{
    const char *v = "STUDENT  \t  ID   \t  126345";
    int id; 
    char string1[100],string2[100];

    sscanf(v, "%s %s %d", string1, string2, &id);
    printf("'%s' '%s' %d\n", string1, string2, id);
    return 0;
}

which prints

$ ./a 
'STUDENT' 'ID' 126345

In general the most robost solution would be to read line by line with fgets and parse the line with sscanf as you have more control over when a line has a wrong format:

char buffer[1024];
while(fgets(buffer, sizeof buffer, stdin))
{
    int id; 
    char string1[100],string2[100];
    if(sscanf(buffer, "%99s %99s %d", string1, string2, &id) != 3)
    {
        fprintf(stderr, "Line with wrong format\n");
        break;
    }

    // do something with read values
}

edit

User Weather Vane points out that the line might have 3 or 4 values, then you could do this:

char buffer[1024];
while(fgets(buffer, sizeof buffer, stdin))
{
    int id; 
    char string1[100],string2[100],string3[100];
    res = sscanf(buffer, "%99s %99s %99s %d", string1, string2, string3, &id);

    if(res != 4)
    {
        int res = sscanf(buffer, "%99s %99s %d", string1, string2, &id);

        if(res != 3)
        {
            fprintf(stderr, "Line with wrong format, 3 or 4 values expected\n");
            break;
        }
    }


    if(res == 3)
        printf("'%s' '%s' %d\n", string1, string2, id);
    else
        printf("'%s' '%s' '%s' %d\n", string1, string2, string3, id);

}

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