【发布时间】:2018-05-24 16:50:56
【问题描述】:
我的目标是读取包含一些列(这里只有两列)的文本文件,并将整个列存储在向量中。第 1 列存储在 column1 中,第 2 列存储在 column2 中,依此类推。
#include <iostream>
#include <fstream>
#include <vector>
/* ======= global variables ======= */
double col1;
double col2;
std::vector<double> column1;
std::vector<double> column2;
readingFile 函数首先检查是否存在打开文件问题。此外,它会在文件不在末尾时读取文本文件。
我的问题是只有第一行可以正常工作。在推回 col3 中的最后一个条目后,它会跳过第 1 列的第一个条目,因此整个数据结构会发生变化。应该存储在第 2 列中的数据存储在第 1 列中,依此类推。
double readingFile()
{
std::ifstream infile("file.txt");
if(!infile)
{
std::cerr << "* Can't open file! *" << std::endl;
return 1;
}
else
{
// skipping first two lines.
infile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
infile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
while(infile >> col1 >> col2 >> col3)
{
column1.push_back(col1);
column2.push_back(col2);
column3.push_back(col3);
}
}
infile.close();
return 0;
}
以下是一些数据的示例:
//There is some text before the actual numbers,
//like the name of the creator of the file. Thats why i'm "ignoring" the first two line out.
1.2 3.4 4.6
0.9 0.4 7.1
8.8 9.2 2.6
第一行工作正常。 col1 持有 1.2 col2 持有 3.4 而 col3 持有 4.6。 但随后 0.9 被跳过,col1 保持 0.4,col2 保持 7.1,依此类推。
【问题讨论】:
-
不要在
while(!input.eof())上循环 -
这里是不做的原因
while(!input.eof()):stackoverflow.com/questions/5605125/… -
您是否尝试调试过您的代码?
-
是的,我做到了。如前所述,第二行的第一个数字被跳过,整个数据结构发生变化。我认为这个问题与 ignore() 函数有关。但我需要跳过前两行。
-
你正在将
col3推送到column1,看起来像是错字
标签: c++ vector fstream ifstream