我正在尝试读取以下格式的文本文件:
5
1.00 0.00
0.75 0.25
0.50 0.50
0.25 0.75
0.00 1.00
代码是:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
int totalDataPoints; // this should be the first line of textfile i.e. 5
std::vector<double> xCoord(0); //starts from 2nd line, first col
std::vector<double> yCoord(0); //starts from 2nd line, second col
double tmp1, tmp2;
int main(int argc, char **argv)
{
std::fstream inFile;
inFile.open("file.txt", std::ios::in);
if (inFile.fail()) {
std::cout << "Could not open file" << std::endl;
return(0);
}
int count = 0;
while (!inFile.eof()) {
inFile >> tmp1;
xCoord.push_back(tmp1);
inFile >> tmp2;
yCoord.push_back(tmp2);
count++;
}
for (int i = 0; i < totalDataPoints; ++i) {
std::cout << xCoord[i] << " " << yCoord[i] << std::endl;
}
return 0;
}
我没有得到结果。我的最终目标是将其作为函数并将 x、y 值作为类的对象进行调用。
最佳答案
int totalDataPoints;
是一个全局变量,并且由于您没有使用值对其进行初始化,因此它将被初始化为 0。然后在你的 for 循环中
for (int i = 0; i < totalDataPoints; ++i) {
std::cout << xCoord[i] << " " << yCoord[i] << std::endl;
}
自i < totalDataPoints
之后您将要做任何事情( 0 < 0
) 是 false
.我怀疑你打算使用
for (int i = 0; i < count; ++i) {
std::cout << xCoord[i] << " " << yCoord[i] << std::endl;
}
或者有
totalDataPoints = count;
在 for 循环之前。
我还建议您不要使用 while (!inFile.eof())
来控制文件的读取。修复它你可以使用
while (inFile >> tmp1 && inFile >> tmp2) {
xCoord.push_back(tmp1);
yCoord.push_back(tmp2);
count++;
}
这将确保循环仅在有数据可读时运行。有关详细信息,请参阅:Why is “while ( !feof (file) )” always wrong?
关于c++ - 从制表符分隔文件中读取二维数据并存储在 vector C++ 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33551634/