在C中使用scanf时输出无限字符'p'

问题描述 投票:1回答:2

我做了一个程序来计算input.txt中的数字:

input.txt中

13 1 17 3 14 10 18 18 16 13 15 5 5 6 12 8 8 3 2 5 4 10 11 3 1 5 10 1 7 5 6 10 9 4 3 10 15 13

main.c中

#include<stdio.h>

int main()
{
    FILE *fptr;
    fptr=fopen("input.txt","r");
    int data;
    int count=0;
    while(!feof(fptr))
    {
        fscanf(fptr,"%d",&data);
        count++;
    }
    printf("%d",count);
}

结果是无限的字符'p'???

https://i.stack.imgur.com/oXlv8.jpg

c
2个回答
1
投票

这有效:

#include <stdio.h>

int main(void) {
    FILE *fptr;
    if (!(fptr = fopen("input.txt", "r"))) {
        printf("Could not open file\n");
        return 1;
    }
    int data, count;
    for (count = 0; fscanf(fptr, "%d ", &data) == 1; count++)
        ;

    printf("%d\n", count);
    fclose(fptr);
    return 0;
}

请注意我对您的代码进行的以下调整。

  • 您没有进行任何错误检查以查看“input.txt”是否存在。你不应该编写代码,即使对于那些假设这样的小程序也是如此。如果输入文件不存在,此程序现在打印错误消息并返回1到shell。
  • while (!feof(fptr))是不好的做法,往往不起作用。要检查文件中是否有剩余数据,请使用scanf()语句本身作为循环条件。为了方便和高效,我做了一个for循环。
  • 你没有在文件指针上执行fclose()。这是绝对必要的,因为您不希望文件指针在内存中浮动,并且您希望系统/ shell知道该文件不再使用。
  • int main()应该在成功时返回0。

如果你这样做,我可以认为你的编译器或二进制文件没有理由像这样打印“pppppp”。如果它继续这样做,则编译器或工作空间有问题。


0
投票

以下提议的代码:

  1. 在当前场景中通过在打开的文件上调用fclose()来清理自己
  2. 在调用时正确检查错误:fopen()fscanf()
  3. 正确使用fscanf()返回的值进行循环控制
  4. 记录为什么包含每个头文件
  5. 使用'\ n'结束printf()格式字符串,以便数据立即传递到终端,而不是等待程序退出。

现在建议的代码:

#include <stdio.h>   // fopen(), fclose(), fscanf(), perror(), printf()
#include <stdlib.h>  // exit(), EXIT_FAILURE


int main( void )
{
    FILE *fptr = fopen("input.txt","r");
    if( ! fptr )
    {
        perror( "fopen failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, fopen successful

    int data;
    int count=0;

    while( 1 == fscanf(fptr,"%d",&data) )
    {
        count++;
    }

    printf("%d\n",count);

    fclose( fptr );
}
© www.soinside.com 2019 - 2024. All rights reserved.