从文件中读取不同类型的变量(每行1个)

Read from a file different types of variables (1 per line)

本文关键字:变量 每行 1个 同类型 文件 读取      更新时间:2023-10-16

我有一个用C++编写的应用程序,它从extern txt文件中获取一些参数。这个文件每行有一个变量,它们是不同的类型,比如:

0
0.8
C: \Documents\Textfile.txt
9

我试过这样的东西(不完全是因为我现在没有代码)

    FILE* f;
char line[300];
f = fopen("parameters.txt", "r");
    scanf(line, val1);
    scanf(line, val2);
    scanf(line, val3);
    fclose(f);

但它不起作用,也尝试过fgets和fgetc进行一些更改,但没有起作用。有什么帮助或想法吗?变量总是相同的数字,每个地方都有相同的类型(所以我认为我不需要任何while或循环)。非常感谢你在这个让我抓狂的新手问题上的帮助。

编辑:事实上,这正是我在的另一个解决方案中看到的代码

sscanf(line, "%99[^n]", tp);
sscanf(line, "%99[^n]", mcl);
sscanf(line, "%99[^n]", pmt);
sscanf(line, "%99[^n]", amx);

它不起作用,它编译了,但程序崩溃了,所以我把它改成scanf,它没有崩溃,但变量是空的。

由于您使用的是C++(而不仅仅是C),我建议您使用标准iostreams库,而不是C stdio。特别是,std::ifstream擅长从文件中读取格式化数据。

#include <fstream>
#include <string>
// ...
std::ifstream f("parameters.txt");
int val1;
f >> val1;
double val2;
f >> val2;
std::string val3;
std::getline(f, val3);
// etc

根据您的应用程序,您可能还需要进行错误检查。看见http://www.cplusplus.com/reference/iolibrary/有关iostream的详细信息。

scanf用于读取stdin的输入,与FILE无关。

如果你想逐行阅读文本文件,我不推荐FILE。它更复杂,更适合二进制读取。我会选择ifstream,这里有一个非常简单的例子:

#include <iostream>
#include <fstream>
using namespace std;
int main(void) {
    ifstream stream("parameters.txt");
    string line;
    /* While there is still a line. */
    while(getline(stream, line)) {
        // variable 'line' is now filled with everyone on the current line,
        // do with it whatever you want.
    }
    stream.close();
}