gpt4 book ai didi

C 文件读取不会读取字符串中的数字数组

转载 作者:行者123 更新时间:2023-11-30 15:21:24 25 4
gpt4 key购买 nike

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

1006 00600016 43212983 50016 06040086 0102111

My code reads the first integer pretty well but the not the 7 digit number? Any help?

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

你需要

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

关于C 文件读取不会读取字符串中的数字数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29574098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com