Search code examples
ctextscanf

Reading text line by line and word by word. C programming


#include <stdio.h>
#include <string.h>
#define KIEK 100
#define MAXSTRING 255
 
int main()
{
     int i=0, l;
     char line[MAXSTRING], duom[12], rez[12], wrd[MAXSTRING], lastchar,e;
     FILE *f, *r;
 
     puts("Enter the input file name:");
     scanf( "%s", duom);
     if (( f = fopen (duom, "r")) == NULL)
         printf("Cannot open the file \"%s\"\n ", duom);
     else
     {
         puts("Enter the input file name:");
         scanf("%s", rez);
         if((r = fopen (rez, "w")) == NULL)
             printf("Cannot create the result file \"%s\"\n ", rez);
         else
         {
             fgets(line, MAXSTRING, f);
             printf("%s",line);
 
             do
             {
                 e = sscanf(line, "%s", wrd);
                 printf("%s",wrd);
                 l = strlen(wrd);
                 i = i+l;
                 lastchar = line[i];
                 printf("%c%d",lastchar,i);
            }
            while(lastchar != '\n');
        }
        fclose(f);
        fclose(r);
    }
}

What this should do is to read line from a text file, for example:

apples and oranges

i love trains

This is not working.

And then it should read each individual word until it finds the \n symbol. But it always reads the first one. What should I do?


Solution

  • replace

    do
    {
        e = sscanf(line, "%s", wrd);
        printf("%s",wrd);
        l = strlen(wrd);
        i = i+l;
        lastchar = line[i];
        printf("%c%d",lastchar,i);
    }
    while(lastchar != '\n');
    

    with

    //There is a need to update the `line` of 1st argument.
    for(i=0; 1==sscanf(line + i, "%s%n", wrd, &l); i = i + l){
        printf("%s\n",wrd);
    }