Sep 26, 2012 at 8:07pm UTC
Hi,
I'm trying to code a programme and I'm getting this code when compiling
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::replace
Aborted (core dumped)
And the problem arising in due to this part of code
result.
replace (pos, key.size(), nkey)
This is part of a larger code.
Can anyone help with me what could be problem.
PS: I had no issue with this code on another Linux machine.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
int ApplicationHandler::CountStrings(const string input, const string key)
{
unsigned int start = 0;
int c = 0;
while (true )
{
start = input.find(key.c_str(), start + 1) ;
if (start == string::npos)
break ;
c++;
}
return c ;
}
string ApplicationHandler::ReplaceString(const string input, const string key, const string nkey)
{
string result = input;
unsigned int pos;
while (true )
{
pos = result.find(key);
if (pos == string::npos)
break ;
result.replace(pos, key.size(), nkey);
}
return result;
}
Last edited on Sep 26, 2012 at 8:09pm UTC
Sep 26, 2012 at 8:28pm UTC
I do not see any problem with ReplaceString except that it would be better to define pos as
std::string::size_type pos;
because it is possible that sizeof( unsigned int ) < sizeof( std::string::size_type )
Try to check
std::cout << sizeof( unsigned int ) << std::endl;
std::cout << sizeof( std::string::size_type ) << std::endl;
Last edited on Sep 26, 2012 at 8:29pm UTC
Sep 26, 2012 at 9:23pm UTC
What is the size of result, the actual value of pos, the size of key and size of nkey when this error occurs? Have you looked?
Sep 27, 2012 at 8:44am UTC
Hi Vlad,
I have used the std::string::size_type pos; instead of unsigned int pos;
The program runs fine without the error but it doesn't quit out of the program itself. It just hangs in there. I have to do Ctrl-C to quit the program.
Any idea?.
Sep 27, 2012 at 9:30am UTC
Could you show what is the result of executing these statemenets?
std::cout << sizeof( unsigned int ) << std::endl;
std::cout << sizeof( std::string::size_type ) << std::endl;
Also it is interesting what compiler are you using?
As for hanging of the program you should show the relevant code.
Sep 27, 2012 at 10:16am UTC
Hi,
When I execute the following statements
std::cout << sizeof( unsigned int ) << std::endl;
std::cout << sizeof( std::string::size_type ) << std::endl;
I get
4
8
respectively.
I'm using latest g++ compiler in Ubuntu.
PS: I had no problem with this program in another linux machine with same set up. So, I cannot understand what is the problem in this machine.
Last edited on Sep 27, 2012 at 12:20pm UTC