我正在尝试逐行读取文件,根据空格对其进行解析并将其放入称为输入的 vector 中。但是,我不能执行 cin >> x1 >> x2 >> x3 ...,因为该行没有一定数量的术语。以下是我的想法,但可能是错误的。
vector <double> input;
fstream inputFile("../Sphere.in", fstream::in);
inputFile.open("../Sphere.in", fstream::in);
while (inputFile.good())
{
getline(inputFile, line);
然后这里的内容表示每行中的空格都放在 input[i] 中
}
我是 C++ 的新手,如果有人能给我提供任何帮助,我将不胜感激。
谢谢,
约翰
最佳答案
如果你只想要一个 double 的平面集合:
#include <vector>
#include <istream> // for operator>>
#include <fstream> // for std::ifstream
std::vector<double> v;
for (double d; inputFile >> d; ) { v.push_back(d); }
或者更简单:
// includes as above
#include <iterator>
std::vector<double> v((std::istream_iterator<double>(inputFile)),
std::istream_iterator<double>());
如果你想要每行一个容器:
// includes as above
#include <string>
#include <sstream>
std::vector<std::vector<double>> v;
for (std::string line; std::getline(inputFile, line); )
{
std::istringstream iss(line);
v.emplace_back(std::istream_iterator<double>(iss),
std::istream_iterator<double>());
}
在逐行方法中,您还可以检查是否已成功到达输入字符串的末尾,或者是否因无效输入而停止并发出诊断信息。如果您想将错误检查发挥到极致,您可以从流中提取单个 strings 并将它们解析为 double
(使用 std::strtod
) 并在失败时发出诊断信息,跳过无法解析的标记:
// ...
#include <cstdlib>
for (std::string line; std::getline(inputFile, line); )
{
std::istringstream iss(line);
v.emplace_back();
for (std::string token; iss >> token; )
{
char * e;
double const d = std::strtod(token.c_str(), &e);
if (*e != '\0') { /* error! skip this token */ continue; }
v.back().emplace_back(d);
}
}
关于C++解析可变长度的 double 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11620833/