【问题标题】:Reading only numbers from a file, from a specific line仅从文件中的特定行读取数字
【发布时间】:2017-10-05 18:43:42
【问题描述】:

我正在尝试从包含 4 行标题的数据文件中读取数据,并且还有一个我将存储到 2d int 数组中的数字列表

例如

标题

标题

标题

标题

int

int

int

int

......

我需要以某种方式跳过这些包含文本的标题行,只使用 int 行并将它们存储到上述二维数组中。当我打开文件并搜索它时,由于一开始的文本,它根本不存储任何值。我已经尝试了多个 if 语句和其他方法来解决这个问题,但到目前为止已经奏效了。

int main()
{

    ifstream imageFile;
    imageFile.open("myfile");

    if (!imageFile.is_open())
    {
        exit (EXIT_FAILURE);
    }

    int test2[16][16];
    int word;
    imageFile >> word;

    while (imageFile.good())
        for (int i = 0; i < 16; i++)
        {

            for (int j = 0; j < 16; j++)
            {

                test2[i][j] = word;
                imageFile >> word;

            }
        }

}

【问题讨论】:

  • getline,getline,getline,getline,阅读其余部分。
  • 或者总是读取字符串,检查格式,然后跳过或格式化为您需要的数据类型(如果标题行数不同)。
  • 这里有两个任务。 1)扔掉前四行,2)读入整数。完成第 1 步后才能执行第 2 步。请执行第 1 步。

标签: c++ arrays ifstream


【解决方案1】:

正如 cmets 中所说,您需要先读取标头 - 这里我只是将标头存储在 trash 变量中,该变量是每次存储新标头时都会被覆盖的字符串:

std::string trash;
for (int i =0; i < 4; i++)
    std::getline(imageFile, trash);

这部分是在您检查文件是否正确打开之后进行的,之后将直接跟随您声明二维数组并读取整数的原始代码。

正如 cmets 中所说,您需要 std::getline 将每个标题行作为一个整体读取,而不是一次读取一个单词,这是我的答案的第一个版本 (imageFile &gt;&gt; trash;)。

【讨论】:

    【解决方案2】:

    您可以通过正则表达式和模式来做到这一点(修改二维数组的代码,这只是您如何从文件或字符串中提取数字的示例):

    std::string ss;
    
    ifstream myReadFile;
    myReadFile.open("foo.txt");
    char output[100];
    if (myReadFile.is_open()) {
        while (!myReadFile.eof()) {
    
            myReadFile >> output;
            ss.append(output);
            ss.append("\n");
    
        }
    }
    myReadFile.close();
    
    std::regex rx(R"((?:^|\s)([+-]?[[:digit:]]+(?:\.[[:digit:]]+)?)(?=$|\s))"); // Declare the regex with a raw string literal
    std::smatch m;
    std::string str = ss;
    while (regex_search(str, m, rx)) {
        std::cout << "Number found: " << m[1] << std::endl; // Get Captured Group 1 text
        str = m.suffix().str(); // Proceed to the next match
    }
    

    输出:

    Number found: 612
    Number found: 551
    Number found: 14124
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-04
      • 1970-01-01
      • 2011-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多