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;
}
答案 0 :(得分:1)
而不是
temp[++count] = '\0';
你需要
temp[count] = '\0';
因为您在count
循环中递增while
。
此外,第一行表示预期会有100
行文本。但是,您只有6
个文本行。之后什么都没读。添加检查以确保在读取失败时停止。
而不是:
fscanf(fp1, "%d", &maxShy);
使用
if ( fscanf(fp1, "%d", &maxShy) != 1 )
{
break;
}
同样,使用:
if ( fscanf(fp1, "%s", temp) != 1 )
{
break;
}