【问题标题】:C file reading doesn't read an array of numbers in as stringC文件读取不会以字符串形式读取数字数组
【发布时间】:2015-04-11 04:23:28
【问题描述】:

fgets() 和 fscanf() 都不起作用,file.txt 有

100 6 0060001 6 4321298 3 5001 6 0604008 6 0102111

我的代码可以很好地读取第一个整数,但不是 7 位数字?有什么帮助吗?

int main(void)
{
    int numTotal = 0;
    int maxShy = 0;
    char temp[101];
    char ch;
    char * ptr;
    int count = 0;

    FILE *fp1 = fopen("file.txt", "r+");
    FILE *fp2 = fopen("output", "w");

    // read the first line, set the total number
    while ((ch = fgetc(fp1)) != '\n')
    {
        temp[count] = ch;
        count++;
    }
    temp[++count] = '\0';
    count = 0;
    numTotal = strtol(temp, &ptr, 10);
    printf("%d", numTotal);


    for (int i = 0; i < numTotal; i++)
    {
        // This part works fine
        fscanf(fp1, "%d", &maxShy);
        printf("%d ", maxShy);

        // This part doesn't outputs a different 7 digit number from 0060001 and others
        fscanf(fp1, "%s", temp);
        printf("%s\n", temp);
    }

    fclose(fp1);
    fclose(fp2);


    system("pause");
    return 0;
}

【问题讨论】:

  • 输出是什么??
  • 这一行:'temp[++count] = '\0';'在 '\0' 字节之前留下一个垃圾字符。建议删除'++'
  • 这一行:'fscanf(fp1, "%s", temp);'不会读取任何内容,因为输入将包含空格字符。建议:'fscanf(fp1, "%s", temp);'请注意格式字符串中的前导空格。格式字符串中的空格将跳过空格,例如两个值之间的空格
  • 输出是断言失败,与字符串有关。

标签: c fgets scanf


【解决方案1】:

代替

temp[++count] = '\0';

你需要

temp[count] = '\0';

因为您在while 循环中递增count

另外,第一行表示需要100 行文本。但是,您只有6 更多的文本行。之后什么都没有读取。添加检查以确保在读取失败时停止。

代替:

fscanf(fp1, "%d", &maxShy);

使用

if ( fscanf(fp1, "%d", &maxShy) != 1 )
{
   break;
}

同样,使用:

if ( fscanf(fp1, "%s", temp) != 1 )
{
   break;
}

【讨论】:

  • 谢谢,我也只粘贴了文本文件的前6行。我应该尝试更改计数。
猜你喜欢
  • 2012-10-06
  • 2016-04-11
  • 1970-01-01
  • 2013-04-13
  • 2015-08-28
  • 1970-01-01
  • 2013-03-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多