如何从C中的.txt文件读取数字 [英] How to read numbers from a .txt file in C

查看:99
本文介绍了如何从C中的.txt文件读取数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何做到这一点,使程序仅从.txt文件中读取字符串中的数字?这样一来,您就可以存储它们并将其用于以后的转换.

How can you make it so the program reads only the numbers in a string from a .txt file? This is so you can then store them and use them for later transformations.

我想我只知道数字是怎么做的,就像您的文件中包含"0.3 0.4"一样:

I think I know how to do it if it were numbers only, like if you had a file that had "0.3 0.4":

fscanf(fp, "%f %f\n", &x, &y);

或者如果它是在每一行中始终相同的字符串.例如,在一个文件中,有几行像这样:"sin(0.348889)= 0.341854".然后,要读取数字,您只需要执行以下操作即可:

Or if it were a string that was always the same in each line. Example, in a file, there's several lines like this one: "sin(0.348889)=0.341854". Then to read the numbers you'd only have to do something like this:

fscanf(fp, "sin(%f)=%f\n", &x, &y);

但是,当字符串并不总是相同时,您将如何做呢?如何从该文件中读取某些数字?我知道要问的问题太多了,但是读书对我没有帮助,我已经尝试过在互联网上搜索,所以我决定投篮了.

But how do you do you do it when the strings are not always the same? How to read certain numbers from that file? I know this is way too much to ask, but reading the book isn't helping me and I already tried searching in the internet, so I decided to take the shot..

推荐答案

通过读取字符,可以不从字符串中跳过数字.像这样:

You can skip not numbers from string by reading chars. Something like this:

int n;
float number;
errno = 0;
while (!errno) {
    n = fscanf(fp, "%f", &number);
    if (n == 1) {
        /* do something with number */
    } else {
        char c;
        n = fscanf(fp, "%c", &c);
        if (n != 1) { /* EOF */
            break;
        }
    }
}

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

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