Ričardas Mikelionis
Ričardas Mikelionis

Reputation: 113

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?

Upvotes: 3

Views: 15665

Answers (3)

BLUEPIXY
BLUEPIXY

Reputation: 40145

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);
}

Upvotes: 0

Gopi
Gopi

Reputation: 19874

Use strtok() to break your line to words using " " as delimiter.

After fetching the line using fgets() use strtok().

char *p = NULL;
while(fgets(line,MAXSTRING,f) != NULL)
{
   p = strtok(line," ");
   while(p != NULL)
   {
      printf("%s ",p); /* your word */
      p = strtok(NULL," ");
   }
}

Upvotes: 3

user411313
user411313

Reputation: 3990

You should use fscanf with %s, it breaks on every whitespace-block, eg. space, newline etc.

...
char word[40];
while( fscanf(f,"%39s",word)==1 )
  puts(word);
...

Upvotes: 1

Related Questions