gpt4 book ai didi

c - 如何读取 C 中以空格分隔的值?

转载 作者:太空狗 更新时间:2023-10-29 16:10:25 25 4
gpt4 key购买 nike

我有一个 .txt 文件,我用它来学习一些基本的 C。

这是txt文件:

8
12 48 15 65 16 82 9 72

这是我的 C 程序:

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



int main(int argc, char** argv){

char num = 0;
//int[] arr = 0;


if (argc != 2){
return 0;
}

FILE *inputFile = fopen(argv[1], "r");

if (inputFile == NULL){
printf("Error1\n");
return 0;
}

while(!feof(inputFile)){
num = fgetc(inputFile);
printf("%c\n",num);
}

if(!feof(inputFile)){
printf("error");
return 0;
}

}

我的目标是根据第一行中的值数量获取第二行的数组....本质上,我们想要一个包含 8 个值的数组,它存储 {12, 48, ....

最佳答案

您使用了错误的函数来读取整数:尽管返回了 int,函数 fgetc 仍在读取单个字符 (why getchar returns an int?)。

为了读取以空格分隔的整数,请改用 fscanf,并检查返回值以确定您已到达文件末尾:

int n;
while (fscanf(inputFile, " %d", &n) == 1) {
printf("%d\n", n);
}

请注意,上面的循环避免使用 feof 来检测文件结束条件 (why using feof is wrong?)

关于c - 如何读取 C 中以空格分隔的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46516806/

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