我有一个文件,里面有这样几行
Bob, 2,3,13,4
Jim 3,4,15,3
...
我试图只将每行中的整数复制到我的数字数组中,这样我就可以用它们做一些数学运算。
问题是,我事先不知道人名后面会有多少数字,但我知道会少于 100。但是,当我运行我的代码时,它会复制 2,3, 13,4 到我的数组中,然后将一堆随机数分配到数组的其他插槽中。我该如何解决这个问题?
我希望它在看到回车后停止复制,我试图通过执行 if (fgetc=!'\r') 之类的 if 语句来做到这一点,但它不起作用,也不适用于'\n'。有人可以帮我解决这个问题吗?
这是我的代码
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *myFile;
myFile = fopen("bob.txt", "r");
//read file into array
int numberArray[100];
int i;
if (myFile == NULL)
{
printf("Error Reading File\n");
exit (0);
}
int k=0;
while(k==0){
if(fgetc(myFile)==',')
k=1;
} //brings pointer to the first number after the first comma
//still need a way to stop copying into array random numbers after the line is done
//so need it to stop after carriage return, but it doesn't work
//also need to start it again after for the next line
for (i = 0; i <100 ; i++)
{
fscanf(myFile, "%d,", &numberArray[i])
}
for (i = 0; i < 100 ; i++)
{
printf("Number is: %d\n\n", numberArray[i]);
}
fclose(myFile);
return 0;
}
最佳答案
fscanf
将返回扫描的项目数;在你的情况下,一旦它返回 0,你就知道你已经完成了该行(因为它无法扫描整数)。
关于c - 如何阻止 fscanf 在行尾时复制到数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26962468/