1

我正在逐字读取文件中的数据,并尝试将其存储在同一个缓冲区中,每个单词之间都有空格。但是,没有空间的话就出来了。请告诉我有什么问题吗?输出即将到来 aniljaiswalvikaskumarnikhilkumarindia 但我希望每个单词之间有空格。

int main()
{
    char buff[200];
    int l=0;
    FILE *fp;
    fd = NULL;``
    fp = fopen("header.c","r");
    memset(buff,0,200);
    while(1)
    {
        fscanf(fp,"%s",buff+l);
        l=strlen(buff);
        printf("Word of string = %s\n",buff);
        printf("Length of string = %d\n",l);
        if(feof(fp))
        {
            break;
        }
    }
    fclose(fp);
    return 0;
}
4

2 回答 2

1

Ignoring the fact that you are exposed to buffer overflow, you can simply add the space:

fscanf(fp,"%s",buff+l);
l=strlen(buff);
buff[l] = ' ';
l++;
于 2012-11-01T18:30:14.893 回答
0

完整的工作代码:

    #include<stdio.h>
    #include<string.h>

     int main()
        {
            char buff[200];
            FILE *fp;
            char c;
            int len=0;
            int i=0;
            fp = fopen("header.c","r");
            memset(buff,0,200);
            while((c=fgetc(fp))!=EOF)
            {
                len++;
                buff[i++]=c;
                if(c==' ' || c=='\n')
                {
                printf("Word of string = %s\n",buff);
                printf("Length of string = %d\n",len);
                }
            }

            fclose(fp);
            return 0;
        }
于 2012-11-01T18:21:13.590 回答