【发布时间】:2015-11-05 18:01:16
【问题描述】:
我正在尝试读取以下格式的文本文件:
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 值作为类的对象调用。
【问题讨论】:
-
您永远不会将
totalDataPoints设置为任何内容。类似:C++ read from file -
请不要测试
if(stream.fail())或if(stream.eof()),除非您知道自己在做什么。只需测试if(stream)。 -
当您在调试器中单步执行此代码时发生了什么?符合您的预期吗?
标签: c++ vector text-files fstream