简体   繁体   English

如何从C中的.txt文件读取数字

[英]How to read numbers from a .txt file in C

How can you make it so the program reads only the numbers in a string from a .txt file? 如何使程序从.txt文件中仅读取字符串中的数字? This is so you can then store them and use them for later transformations. 这样一来,您便可以存储它们并将其用于以后的转换。

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": 我想我只知道数字就知道该怎么做,就像您的文件带有“ 0.3 0.4”一样:

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

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". 例如,在一个文件中,有几行像这样:“ 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;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM