我正在尝试读取格式为的文本文件:
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值称为类的对象。
答案 0 :(得分:1)
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?
答案 1 :(得分:1)
只需在代码中进行简单的更改即可。您无法从第一行的totalDataPoints
获取file.txt
。然后你走完每条线直到最后。
int count = 0;
inFile>>totalDataPoints;
while (!inFile.eof()) {
inFile >> tmp1;
xCoord.push_back(tmp1);
inFile >> tmp2;
yCoord.push_back(tmp2);
count++;
}
通过 for循环,你可以这样做,这里int count = 0
是不必要的:
inFile>>totalDataPoints;
for (int i=0; i<totalDataPoints; i++)
{
inFile >> tmp1;
xCoord.push_back(tmp1);
inFile >> tmp2;
yCoord.push_back(tmp2);
}