简体   繁体   English

std :: string :: substr抛出std :: out_of_range但参数是限制的

[英]std::string::substr throws std::out_of_range but the arguments are in limit

I have a vector of strings: 我有一个字符串向量:

vector<string> tokenTotals;

When push_back is called, a string of length 41 is stored and I must operate on each element of my vector and get two substrings, the first in range 0 to 28 and the second in range 29 to 36: 当调用push_back ,存储一个长度为41的字符串,我必须对向量的每个元素进行操作并获得两个子字符串,第一个在0到28范围内,第二个在29到36范围内:

for(int i = 0; i < tokenTotals.size(); i++)
{
    size_t pos = tokenTotals[i].find(": ");
    cout << tokenTotals[i] << endl; // Show all strings - OK
    cout << tokenTotals[i].length() << endl; // Lenght: 41
    string first  = tokenTotals[i].substr(0, 28); // OK
    string second = tokenTotals[i].substr(29, 36); // ERROR
    cout << first << " * " << second << endl;
}

But when I try to get the second substring, I get the following error: 但是当我尝试获取第二个子字符串时,我收到以下错误:

terminate called after throwing an instance of std::out_of_range.
what():: basic_string::substr

Any idea of what could have happened? 知道会发生什么事吗?

See the std::string::substr reference . 请参阅std::string::substr引用 The second parameter is the length of the substring, not the position of the character after the substring, so the result is an attempt to access elements out of range - std::out_of_range is thrown. 第二个参数是子字符串的长度而不是子字符串后字符的位置 ,因此结果是尝试访问超出范围的元素 - 抛出std::out_of_range

With tokenTotals[i].substr(0, 28) this mistake doesn't manifest, since the substring has both size and the position one past end 28. 使用tokenTotals[i].substr(0, 28)这个错误不会显现出来,因为子字符串既有大小又有一个位于结尾28的位置。

substr(29,36);

will attempt to get a string that starts at position 29 and has a size of 36 characters. 将尝试获取从第29位开始并且大小为36个字符的字符串。 Unfortunately 29 + 36 > 41 不幸的是29 + 36> 41

documentation 文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM