首页 > 解决方案 > C++ 文件逐行读取

问题描述

我正在尝试逐行读取文件。我的文件有点像这样:

一个 4 558 5

123 145 782

x 47 45 789

如果第一个字符是 a,我想将它前面的三个值存储在一个数组中。我正在尝试这个,但它似乎不起作用:

 while (std::getline(newfile, line))
    {
        if (line[0] == 'a')
        {
            vertex[0] = line[1];
            vertex[1] = line[2];
            vertex[2] = line[3];
            //vertices.push_back(vertex);
        }

标签: c++filegetline

解决方案


我正在尝试这个,但它似乎不起作用:

当你使用

vertex[0] = line[1];

的第 1 个字符line分配给vertex[0]。这不是你的本意。您想将a行中的第一个数字分配给vertex[0]

您可以使用std::istringstream来提取数字。

if (line[0] == 'a')
{
   // Make sure to ignore the the first character of the line when
   // constructing the istringstream object.

   std::istringstream str(&line[1]);
   str >> vertex[0] >> vertex[1] >> vertex[2];
}

推荐阅读