说实话,我并不完全了解您输入文件的结构以及您想要实现的目标。人们确实很想帮助你,因此我建议添加更多数据。
您还应该在发布之前编译您的程序。它会告诉你已经有一些语法错误。不用编译我可以告诉你有
- 打开函数后缺少分号
- 打开函数中双引号中没有字符串
- 最后一个语句中的大写 Z
编译器会向您显示所有这些错误。而且,如果您想从 SO 成员那里获得帮助,您至少应该提供已编译的代码。 . .
如前所述。我不知道你想做什么。无论如何,请看下面的例子:
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
int main()
{
// Open the input file
std::ifstream file("yourFileName.txt");
// We must check, if the file could be opened
if (file) {
std::string oneLine{};
// Read all lines from file
while(std::getline(file, oneLine)) {
// Copy line to a stringstream, so that we can extract the data fields
std::istringstream issLine(oneLine);
// Define Variables that will be read from the line
double x{0.0}, y{0.0}, z{0.0};
std::string date{};
// Extract the requested data
issLine >> date >> x >> y >> z;
//
// Do some work with that data
//
}
}
else {
std::cerr << "Could not open Input file\n";
}
return 0;
}
所以首先我们定义一个 ifstream 类型的变量文件,并将文件名作为其构造函数的参数。这会尝试打开文件。当变量超出范围时,析构函数将自动关闭文件。
然后我们检查文件是否可以打开。这行得通,因为! ifstream 的运算符已重载。如果文件无法打开,则会显示错误消息。
接下来我们使用 getline 函数从文件中读取一个完整的行。我们将在 while 循环中执行此操作,以便我们逐行读取,直到读取完文件中的所有行。
现在有点棘手。因为我们要提取数据,所以我们将读取的行复制到 istringstream 对象。我们可以从这样的对象中提取数据。
然后我们提取所有数据,您可以用它做任何您想做的事情。
请查看我在互联网上使用的所有功能并获得并理解。阅读 C++ 书籍。
希望这会有所帮助。