gpt4 book ai didi

c - 从文件 c 中读取多位整数

转载 作者:太空宇宙 更新时间:2023-11-04 00:37:42 24 4
gpt4 key购买 nike

所以我有一个名为 num.txt 的文本文件,其中有一串由空格分隔的整数。

假设 num.txt 包含:5 3 21 64 2 5 86 52 3

我想以读取格式打开文件并获取数字。所以我可以说

int iochar;
FILE *fp;

fp = fopen("num.txt", "r");
while ((iochar=getc(fp)) !=EOF){
if(iochar!=' '){
printf("iochar= %d\n", iochar); //this prints out the ascii of the character``
}

^这适用于个位数。但是我应该如何处理两位数或三位或更多位数的数字呢?

最佳答案

使用 strtol() 解析整数列表:

char buf[BUFSIZ];

while (fgets(buf, sizeof buf, stdin)) {
char *p = buf;

while (1) {
char *end;

errno = 0;
int number = strtol(p, &end, 10);

if (end == p || errno) {
break;
}

p = end;

printf("The number is: %d\n", number);
}
}

如果你想解析 float ,使用strtod()

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

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