gpt4 book ai didi

c - 从文本文件中读取数字并将其用作输入

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

我有这样的文字:

0 0 0 0 0 1
0 0 0 0 1 1
0 0 0 1 0 1
0 0 0 1 1 1

我想读取每行的前 5 个数字,然后将它们用作函数的输入。

我是 c 语言新手,只完成了这段代码,如果真的有什么作用的话,它并没有做太多事情。

    int v,o;
FILE *mydata;

if ((mydata = fopen("testinputs.txt", "rt"))==NULL)
{
printf ("file can't be opened'\n");
exit(1);}


fclose(mydata);

我该如何完成它?

谢谢。

最佳答案

好吧,假设您的文件名为“input.txt”,那么这就是您需要做的:

#include <stdio.h>
#include <stdlib.h>

#define LINE_LEN 100
int main ( void )
{
char line[LINE_LEN];
int sum, i, read_cnt, numbers[5];//sum and i are there for my example usage
FILE *in = fopen("input.txt", "r");//open file
if (in == NULL)
{
fprintf(stderr, "File could not be opened\n");
exit( EXIT_FAILURE);
}
while((fgets(line, LINE_LEN, in)) != NULL)
{//read the line
//scan 5 numbers, sscanf returns the number of values it managed to extract
read_cnt = sscanf(
line,
"%d %d %d %d %d",
&numbers[0],
&numbers[1],
&numbers[2],
&numbers[3],
&numbers[4]
);
//check to see if we got all 5 ints
if (read_cnt != 5)
printf("Warning: only read %d numbers\n", read_cnt);//whoops
//just an example, let's add them all up
for (sum= i=0;i<read_cnt;++i)
sum += numbers[i];
printf("Sum of numbers was: %d\n", sum);
}
return EXIT_SUCCESS;
}

使用此 input.txt 文件:

1 2 3 4 5 
2 2 2 2 2
1 23 2 3 4
12 23

这为我们提供了以下输出:

Sum of numbers was: 15
Sum of numbers was: 10
Sum of numbers was: 33
Warning: only read 2 numbers
Sum of numbers was: 35

这应该足以让您开始使用

关于c - 从文本文件中读取数字并将其用作输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23542088/

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