使用ifstream getline意外退出循环

时间:2016-11-22 04:22:09

标签: c++ file-io while-loop ifstream getline

请查看以下代码:

std::string s;
while(std::getline(m_File,s))
{
    std::cout<<"running\n";
    std::string upper(s);
    std::transform(upper.begin(),upper.end(),upper.begin(),toupper);


    if(upper.find("*NODE") != std::string::npos)
    {
        std::cout<<"start reading nodes\n";
        readnodes();

    }
    std::cout<<"\n open? "<<m_File.is_open()<<"\n";

}

我试图从下面的输入文件中提取数据。( INPUT FILE

 *NODE
 1 ,1.0,2.0
 2, 2.6,3.4
 3, 3.4, 5.6
 *NODE
 4, 4, 5
 5, 5, 6

但是当我运行它时,程序会找到 * NODE的第一个实例并调用readnode()函数,但是无法识别* NODE的第二个实例。 m_File是同一类的ifstream对象,其中readnode()被定义为私有函数。

readnode():

 void mesh::readnodes()
 {
 char c;                                              
 int id;
 float x,y;

   while(m_File>>id>>c>>x>>c>>y)
   {
    node temp(id,x,y);
    m_nodes.push_back(temp);

    // dummy string for reading rest of line. 
    std::string dummy;
    std::getline(m_File,dummy);

   }
}

2 个答案:

答案 0 :(得分:1)

为什么意外退出?

while(m_File>>id>>c>>x>>c>>y)
{
    node temp(id,x,y);
    m_nodes.push_back(temp);

    // dummy string for reading rest of line. 
    std::string dummy;
    std::getline(m_File,dummy);
}

在上面的代码中,m_File>>id>>c>>x>>c>>y用于读取id,x,y,但在读取前几个节点行后,它会在m_File>>id>>c>>x>>c>>y失败时中断,这也可能会更改{{1}国家。结果,m_File返回false,导致意外退出。

解决方案:

我没有遇到基于原始程序的解决方案。但是既然你想从字符串中提取值,那么 boost 可能是更好的解决方案,请检查:

getline(m_File, s)

获取结果:

while (getline(m_File, s))
{
    if (boost::to_upper_copy(s) == "*NODE") continue;

    std::vector<std::string> SubStr;
    boost::algorithm::split(SubStr, s, boost::is_any_of(" ,"));

    SubStr.erase(std::remove(SubStr.begin(), SubStr.end(), ""), SubStr.end());
    m_nodes.push_back(node(atoi(SubStr[0].c_str()), atof(SubStr[1].c_str()), atof(SubStr[2].c_str())));
}
  

输出

for (auto Itr : m_nodes)
    std::cout << Itr.id << "," << Itr.x << "," << Itr.y << std::endl;

答案 1 :(得分:0)

感谢您在readnode()函数中找出while循环条件中的错误。 更好的解决方案是更改readnode()函数,如下所示。

void mesh::readnodes()
{
char c;                         //temp.variable for recieving ','.
int id;
float x,y;
std::string temp;

// changes made in the while loop condition
while(m_File.peek() != '*' and m_File.peek() != EOF )
{
    //getline(m_File,temp);
    m_File>>id>>c>>x>>c>>y;
    node temp(id,x,y);
    m_nodes.push_back(temp);

    // dummy string for reading rest of line.
    std::string dummy;
    std::getline(m_File,dummy);

}
}