gpt4 book ai didi

c - 从 C 文件中读取整数

转载 作者:太空宇宙 更新时间:2023-11-04 07:17:32 25 4
gpt4 key购买 nike

所以我想读取一个包含整数的文件。我可以阅读第一个数字,但如何才能阅读所有数字?字符串很简单,但这是不同的。我还想以一种稍后可以将它们加在一起的方式阅读它们。我编辑了我的代码并且能够输出它们,但我的另一个问题是如何单独选择每个数字以便我可以添加任何我想要的。例如,如果我只想选择第一列并将其添加在一起。

数据:

54 250 19  
62 525 38
71 123 6
85 1322 86
97 235 14

代码:

#include <stdio.h>
#include <conio.h>

int main()
{
// pointer file
FILE *pFile;
char line[128];

// opening name of file with mode
pFile = fopen("Carpgm.txt","r");

//checking if file is real and got right path
if (pFile != NULL)
{

while (fgets(line, sizeof(line), pFile) != NULL)
{
int a, b, c;

if (sscanf(line, "%d %d %d", &a, &b, &c) == 3)
{
/* Values read, do something with them */
printf("%d %d %d\n",a, b, c);
}
}

//using fgets to read with spaces
//fgets(line,81, pFile);

//printing the array that got the pfile info

//closing file
fclose(pFile);
}
else
{
printf("Could not open file\n");
}

getch();
return 0;
}

最佳答案

使用 fgets 读取整行然后使用 sscanf “解析”该行.

有点像

char line[128];
while (fgets(line, sizeof(line), pFile) != NULL)
{
int a, b, c;

if (sscanf(line, "%d %d %d", &a, &b, &c) == 3)
{
/* Values read, do something with them */
}
}

关于c - 从 C 文件中读取整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23421536/

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