【问题标题】:Reading text file issue with c++ ifstream用c ++ ifstream读取文本文件问题
【发布时间】: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


【解决方案1】:

尝试使用:

while (infile >> col1 >> col2)
{
    column1.push_back(col1);
    column2.push_back(col2);
}

以上是从文件中读取的首选习惯用法。

【讨论】:

  • 这对我来说只适用于第一行。由于无法解释的原因,第一列的第一个数字总是被跳过。所以整个数据结构发生了变化。应该在第 3 列中的数据在第 4 列等中。
  • 请使用输入数据示例编辑您的帖子。第一行可能只有一个数字。
  • 我添加了一个数据的小例子。会不会是因为 infile.ignore() 函数而跳过了一行中的第一个数字?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-28
  • 2011-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-23
相关资源
最近更新 更多