试图用C++编写一个只读取第一列数据并跳到下一行的类

Trying to write a class in C++ that only reads in the first column of data and skips to the next line

本文关键字:数据 一列 一行 读取 C++ 一个      更新时间:2023-10-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();
}

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

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

当您只想读取一行的一部分,并跳过该行的其余部分时,一个简单的起点是:

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

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