从文件c读取多位整数 [英] read multidigit int from file c

查看:143
本文介绍了从文件c读取多位整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个名为num.txt的文本文件,其中包含一串由空格分隔的整数.

So I have a text file called num.txt that has a string of integers separated by a space.

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

So let's say num.txt contains: 5 3 21 64 2 5 86 52 3

我想以读取格式打开文件并获取编号.所以我可以说

I want to open the file in read format and get the numbers. So I can say

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``
    }

^这适用于一位数字.但是我应该如何处理具有两个或三个或三个以上数字的数字?

^this works for single-digit numbers. but how should I handle numbers with two or three or more digits?

推荐答案

使用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);
    }
}

如果要解析浮点数,请使用strtod().

If you wish to parse floating-point numbers, use strtod().

这篇关于从文件c读取多位整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆