【问题标题】:Trying to write a class in C++ that only reads in the first column of data and skips to the next line试图用 C++ 编写一个只读取第一列数据并跳到下一行的类
【发布时间】:2014-11-08 02:09:16
【问题描述】:

这可能是一个非常简单的问题,但我没有找到任何示例来指导我。我正在尝试用 C++ 编写可以读取文本文件的类,其中数据列(float、char、int 等)由空格分隔。我希望班级能够忽略某些列并读取指定的列。现在我正在试验一列和两列格式并从那里取得进展。下面列出了一个测试输入文件的简短示例。

103.816   
43.984    
2214.5    
321.5     
615.8     
8.186     
37.6      

我第一次尝试编写读取一列数据的代码很简单,看起来像这样。

void Read_Columnar_File::Read_File(const std::string& file_name)
{
    int i;
    std::ifstream inp(file_name,std::ios::in | std::ios::binary);
    if(inp.is_open()) {     
    std::istream_iterator<float> start((inp)), end;
    std::vector<float> values(start,end);
    for(i=0; i < 7; i++) std::cout << values[i] << std::endl;
    }
    else std::cout << "Cannot Open " << file_name << std::endl;
    inp.close();
}

在我的下一次尝试中,我尝试仅读取两列格式中的一列,如下所示的输入。这些数字只是为了这个例子而编造的

103.816   34.18
43.984    21.564
2214.5    18.5
321.5     1.00
615.8     4.28
8.186     1.69
37.6      35.48

我稍微修改了代码格式,使其看起来像下面的示例。我在 inp >> 语句之后使用了一个简短但伪代码来说明我试图让代码在阅读第一列后跳到下一行。我的问题是“我如何让代码只读取第一列,然后跳到下一行,它再次读取第一列数据并让它继续这样做直到文件结束?”并提前感谢您提供的任何建议。

void Read_Columnar_File::Read_File(const std::string& file_name)
{
    int i;
    float input;
    std::vector<float> values;
   std::ifstream inp(file_name,std::ios::in | std::ios::binary);
   if(inp.is_open()) {
       for(i=0; i < 7; i++) {
           inp >> input >> \\ - At this point I want the code to skip to the next
                           \\   line of the input file to only read the first column
                           \\   of data
           values.push_back(input);
       }
    for(i=0; i < 7; i++) std::cout << values[i] << std::endl;
    }
    else std::cout << "Cannot Open " << file_name << std::endl;

    inp.close();
}

【问题讨论】:

    标签: c++ c++11 stl stdvector


    【解决方案1】:

    您可以使用成员函数ignore() 丢弃所有字符,直到下一行。我还将修复您的代码以使用基于提取成功的for() 循环,这样您的代码将适用于任意数量的列,而不仅仅是 7:

    for (float input; inp >> input; values.push_back(input))
    {
        inp.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    

    【讨论】:

      【解决方案2】:

      如果您只想阅读一行的一部分并跳过该行的其余部分,一个简单的起点是:

      1. 将整行读入字符串
      2. 将整个字符串放入一个字符串流中
      3. 解析出你关心的部分
      4. 重复

      通常,我发现这比在从文件中读取数据时交替读取和忽略数据更容易概括。

      【讨论】:

      • 这也很好,因为你有这条线,你可以保存你跳过的数据,对于文件流,技术上不能保证是可恢复的。
      • 谢谢你们(你们俩)对我的问题的回答。我希望 C++ 中可能有一个高级命令,例如在 fortran 中,它可以让我在读入特定列后前进到下一行,但似乎并非如此。但是,您的回答仍然很有帮助。请原谅我没有对您的答案进行评分,但我是该网站的新手,我自己的评分还不够高,无法对人们进行评分。
      • 当我尝试更新你们两个时,网站产生了一条消息,指出我必须至少有 15 名代表才能更新某人。
      • @Jon:显然我的记忆是错误的。对不起。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多