从文件中读取不同类型的变量(每行1个)
Read from a file different types of variables (1 per line)
我有一个用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();
}
相关文章:
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- C++ 中的二维整数数组,每行中的元素数量不均匀
- 如何在 CSR 矩阵的对角线块中计算每行的非零数
- fftw:为什么我的 2D DFT 输出与每行的 1D DFT 输出不同?
- 如何找到每行的最大值和最小值
- 每像素字节数,每行字节数-如何在tess二的tessbaseapi.cpp中使用函数nativeSetImageByte
- 阅读每行不同栏目的全文
- 如何创建一个具有可变行且每行有 3 列的 2D 数组?
- C++如何通过忽略每行的第一个字符来读取 unicode 文件
- clang 格式:始终断开所有参数,每行一个
- CIN 会丢失每行的前几个字符
- 检查数组行中每行C++是否始终存在相同的值
- 视觉在C 中获取每行代码的执行时间
- 不稳定的C :每行适应性变化多变量初始化
- 如何计算 2D 数组中每行的总和并放置在向量中
- 如何用 c++ 读取 txt 文件,如果我们不知道其中有多少个数据字符串,以及每行有多长?
- 读取文件并将每行拆分为C++中的多个变量
- QTextStream 将 csv 文件中每行的第一个字符与已知变量进行比较
- 从文件中读取不同类型的变量(每行1个)
- FSCANF 不会读取每行中的第一个变量