得到&#st; :: out_of_range' what():basic_string :: substr,即使pos小于字符串

时间:2015-09-22 00:53:05

标签: substr stdstring outofrangeexception

我正在运行此代码:

*

ifstream trace_file;
trace_file.open (argv[7]);
while (!trace_file.eof())
    {

        string line;
        getline (trace_file,line);
        string read_write = line.substr(0,1);

        string address = line.substr(2);

       cout << line << '\t' << read_write <<  "-->" << address<< "-->" << line.size() << '\n';

    }

*

我通过ifstream阅读的文件包含以下内容:

r 4fd

w f47

r 8d2

w f05

我得到了这个输出:

r 4fd   r-->4fd-->5

w f47   w-->f47-->5

r 8d2   r-->8d2-->5

w f05   w-->f05-->5

terminate called after throwing an instance of 'std::out_of_range'

  what():  basic_string::substr

Abort (core dumped)

如果删除此行,它会正常运行:

 string address = line.substr(2);

每个字符串的长度为5,因此不应抛出此异常。

如果我保持pos = 0

,它运行正常

对于pos = 1或2或3,我得到了这个例外。

我不明白这里有什么问题。任何帮助将不胜感激。

0 个答案:

没有答案
相关问题