逐行阅读文本和逐字逐句阅读。 C编程

时间:2014-12-04 15:06:58

标签: c text lines getline scanf

#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("Iveskite ivesties failo varda:");
     scanf( "%s", duom);
     if (( f = fopen (duom, "r")) == NULL)
         printf("Negalima atverti failo \"%s\"\n ", duom);
     else
     {
         puts("Iveskite isvesties failo varda:");
         scanf("%s", rez);
         if((r = fopen (rez, "w")) == NULL)
             printf("Negalima sukurti rezultato failo \"%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);
    }
}

这应该是从文本文件中读取行,例如:

apples and oranges

i love trains

这不起作用。

然后它应该读取每个单词,直到找到\n符号。但它总是读第一个。我该怎么办?

3 个答案:

答案 0 :(得分:2)

使用strtok()将您的行划分为使用" "作为分隔符的单词。

使用fgets()获取行后,使用strtok()

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

答案 1 :(得分:1)

您应该将fscanf与%s一起使用,它会在每个空格块上中断,例如。空格,换行等。

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

答案 2 :(得分:0)

替换

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

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