使用 C++ ifstream 读取文本文件问题
Reading text file issue with c++ ifstream
我的目标是读取包含一些列(这里只有两列)的文本文件并将整个列存储在向量中。第 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 (infile >> col1 >> col2)
{
column1.push_back(col1);
column2.push_back(col2);
}
以上是从文件中读取的首选习惯用法。
我的目标是读取包含一些列(这里只有两列)的文本文件并将整个列存储在向量中。第 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 (infile >> col1 >> col2)
{
column1.push_back(col1);
column2.push_back(col2);
}
以上是从文件中读取的首选习惯用法。