std :: string :: substr throws std :: out_of_range但是参数是在限制 [英] std::string::substr throws std::out_of_range but the arguments are in limit
问题描述
我有一个字符串向量:
vector<string> tokenTotals;
当调用 push_back
长度41存储,我必须对我的向量的每个元素操作,并获得两个子字符串,第一个在范围0到28,第二个在范围29到36:
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:
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
推荐答案
请参阅 std :: string :: substr
参考。第二个参数是子字符串的长度,子字符串后面的而不是位置,因此结果是尝试访问超出范围的元素 - <$ c
See the std::string::substr
reference. 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.
使用 tokenTotals [i] .substr(0,28)$ c> std :: out_of_range
这个错误不会显示,因为子字符串的大小和位置一个过去的结束28。
With tokenTotals[i].substr(0, 28)
this mistake doesn't manifest, since the substring has both size and the position one past end 28.
这篇关于std :: string :: substr throws std :: out_of_range但是参数是在限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!