为什么我会超出范围错误

时间:2015-12-03 05:55:21

标签: c++ string debugging c++11 io

我有一个包含一组数字的文件,例如20.该文件的内容是社会安全号码,我试图删除每个' - '。虽然在浏览文件时我收到以下错误。

  

libc ++ abi.dylib:以std :: out_of_range类型的未捕获异常终止:basic_string

这是代码

string str;
ifstream inFile (fName);
//fName= name of the file
if (inFile.is_open())
{
    while ( getline (inFile,str) )
    {

        cout << str << endl;
        str.erase(3,1);//erasing first '-'
        str.erase(5,1);//erasing second '-'
        cout << str << endl;
    }
    inFile.close();
}

else
    cout << "Unable to open file";

1 个答案:

答案 0 :(得分:3)

我建议您在代码中添加一些检查,这样您就不会假设有两个'-'位于您希望找到它们的位置。

if ( str.size() >= 4 && str[3] == '-' )
{
   str.erase(3,1);
   if ( str.size() >= 6 && str[5] == '-' )
   {
      str.erase(5,1);
   }
   else
   {
      std::cout << "Did not find a '-' at the 6-th position of the string.\n";
      std::cout << str << std::endl;
   }
}
else
{
   std::cout << "Did not find a '-' at the 4-th position of the string.\n";
   std::cout << str << std::endl;
}
相关问题