c - 如何阻止 fscanf 在行尾时复制到数组中?

标签 c

我有一个文件,里面有这样几行

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/

相关文章:

c - 程序通过C预处理器后,这个声明行会变成什么?

c - 我想知道下面给定代码中的函数返回类型......并解释该代码是如何工作的?

c++ - 为什么 KCacheGrind 不显示我的函数名称?

c - 如何将参数绑定(bind)到 C 函数指针?

c - 在 C 中实现函数列表 + 在它们之间切换的更好方法?

python ctypes,试图找到库名称

c - RSA_generate_key() 使用 prngd 代替/dev/random 或/dev/urandom

html - 如何使用 c 访问网页来维护 Atheros 板上的 session

c++ - 最佳 Base-10 仅 itoa() 函数?

c - 如何在C中检查指针变量的地址