[英]Reading 2D data from tab delimited file and store in vector C++
I am trying to read a text file of the format: 我正在尝试读取以下格式的文本文件:
5
1.00 0.00
0.75 0.25
0.50 0.50
0.25 0.75
0.00 1.00
The code is: 代码是:
#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;
}
I am not getting results. 我没有得到结果。 My final aim is to put this as function and call the x, y values as an object of a class. 我的最终目标是将其作为函数,并将x,y值称为类的对象。
int totalDataPoints;
is a global variable and since you are not initializing it with a value it is going to be 0 initialized. 是一个全局变量,由于您没有使用值对其进行初始化,因此它将被初始化为0。 Then in your for loop 然后在您的for循环中
for (int i = 0; i < totalDataPoints; ++i) {
std::cout << xCoord[i] << " " << yCoord[i] << std::endl;
}
You are going to do anything since i < totalDataPoints
( 0 < 0
) is false
. 您将做任何事情,因为i < totalDataPoints
( 0 < 0
)为false
。 I suspect you meant to use 我怀疑你打算用
for (int i = 0; i < count; ++i) {
std::cout << xCoord[i] << " " << yCoord[i] << std::endl;
}
Or have 或有
totalDataPoints = count;
Before the for loop. 在for循环之前。
I would also suggest you do not use while (!inFile.eof())
to control the reading of the file. 我也建议您不要使用while (!inFile.eof())
来控制文件的读取。 To fix it You can use 要修复它,您可以使用
while (inFile >> tmp1 && inFile >> tmp2) {
xCoord.push_back(tmp1);
yCoord.push_back(tmp2);
count++;
}
This will ensure the loop will only run while there is data to read. 这将确保循环仅在有要读取的数据时才运行。 For more information see: Why is “while ( !feof (file) )” always wrong? 有关更多信息,请参见: 为什么“ while(!feof(file))”总是错误的?
Just a simple change needed in your code. 只需对代码进行简单的更改即可。 You can not take totalDataPoints
which is provide from file.txt
in first line. 您不能在第一行中获取file.txt
中提供的totalDataPoints
。 Then you take every line until reach last. 然后,您将每一行都拿到最后。
int count = 0;
inFile>>totalDataPoints;
while (!inFile.eof()) {
inFile >> tmp1;
xCoord.push_back(tmp1);
inFile >> tmp2;
yCoord.push_back(tmp2);
count++;
}
By for loop you can do this like, Here int count = 0
is unnecessary: 通过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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.