【问题标题】:Unhandled exception when using getline [duplicate]使用getline时未处理的异常[重复]
【发布时间】:2018-06-19 22:33:52
【问题描述】:

在使用getline 函数后尝试获取第一个字母时,我不断收到 Unhandled 异常。

错误:

Lab2 中 0x7535DB52 处的未处理异常 - 容器和 Regex.exe: Microsoft C++ 异常:内存位置的 std::out_of_range 0x00B5F43C。


class CodeMap
{
private:
    vector<string> code;
    vector<char> character;

public:
    CodeMap() { character.resize(11000); }
    ~CodeMap() {};

    void setChar(string filename)
    {
        string fileName = filename;
        ifstream fin;
        fin.open(fileName.c_str());
        string line = " ";
        char codeChar;

        while (!fin.eof())
        {
            getline(fin, line);
            codeChar = line.at(0);  //Unhandled exception, tried to use [] instead, still error.

        }
        fin.close();

    }

我想知道这里发生了什么。

无论如何要解决这个问题?

感谢您的帮助。

【问题讨论】:

标签: c++ string getline


【解决方案1】:

正如链接的答案所说(在@NeilButterworth 的评论中),只有在最后一次读取“失败”时,您才能使用 EOF 条件来确定是否可以进行另一次读取。在上面的代码中,当 getline 最终失败时(它),您将有一个空的 line 变量,然后您可以对其进行访问。

尝试改用while(std::getline(fin, line)) { ...。这样,当 getline 失败时,您就不会使用(空)line 的内容。

【讨论】:

  • 解决问题!非常感谢!
  • getline() 可以成功并且仍然返回一个空字符串,如果文件中有空行的话。最好在调用 at(0) 之前检查一个空白字符串
猜你喜欢
  • 1970-01-01
  • 2012-09-04
  • 2018-10-16
  • 2014-06-24
  • 1970-01-01
  • 1970-01-01
  • 2018-10-15
  • 1970-01-01
  • 2015-12-17
相关资源
最近更新 更多