Search code examples
cfilesubstringscanfc-strings

reading input from .txt file in C


john smith 21 VETERAN 1

I have a .txt file writing this . I want to read this .txt file and take john smith as a variable . but I can't read with whitespaces.

edit: I want to take john smith and print it in the console with

printf("%s",name); I tried code below but didnt work. only takes smith.

while (fscanf(file, "%s, %d %s %d", name, &age, priorityGroup, &priorityLevel) == 4)

edit2:


Solution

  • The task is not easy for beginners learning C.

    There can be different approaches.

    I can suggest the following approach.

    At first a full record is read from the file using standard C function fgets as for example

    char record[100];
    
    fgets( record, sizeof( record ), fp );
    

    Now let's assume that the record is already read. Then to output the first two words in record you can use standard C function sscanf as shown in the demonstration program below.

    #include <stdio.h>
    
    int main( void )
    {
        char record[] = "john smith 21 VETERAN 1\n";
    
        int n = 0;
    
        for (size_t i = 0; i < 2; i++)
        {
            const char *p = record + n;
            int m;
    
            sscanf( p, "%*s%n", &m );
    
            n += m;
        }
    
        printf( "\"%.*s\"\n", n, record );
    }
    

    The program output is

    "john smith"
    

    Or you could make a string of the two words just writing

    record[n] = '\0';
    printf( "\"%s\"\n", record );
    

    Or if your compiler supports variable length arrays you could write

    #include <string.h>
    
    //...
    
    char name[n + 1];
    
    memcpy( name, record, n );
    name[n] = '\0';
    
    printf( "\"%s\"\n", name );
    

    If the compiler does not support variable length arrays then you will need to allocate an array dynamically like for example

    #include <string.h>
    #include <stdlib.h>
    
    //...
    
    char *name = malloc( n + 1 );
    
    memcpy( name, record, n );
    name[n] = '\0';
    
    printf( "\"%s\"\n", name );
    

    In this case do not forget to free the allocated memory when it will not be required any more

    free( name );
    

    In the demonstration program the string literal used as an initializer of the array record is appended with the new line character '\n' because the function fgets itself can store this character in the destination array.