Robert J Robert J - 2 months ago 33
C++ Question

Out of bounds with find and replace in C++

I seem to be running into an odd situation that I do not undersand in C++. When I execute a function that parses and replaces strings (Roman Numerals). I end up going out of bound if the string is not present:

Terminal output:



Mac Shell: CPP/>$ ./Roman2Num

Retrieving input:
------------------
Enter a number: 24
input: XXIV
libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string
Abort trap: 6
Mac Shell: CPP/>$ ./Roman2Num

Retrieving input:
------------------
Enter a number: 29
input: XXVIV
Roman: XXIX
Mac Shell: CPP/>$ ./Roman2Num

Retrieving input:
------------------
Enter a number: 1999
input: MDCDLXLVIV
Roman: MDCDLXLIX
Mac Shell: CPP/>$ ./Roman2Num

Retrieving input:
------------------
Enter a number: 1998
input: MDCDLXLVIII
libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string
Abort trap: 6
Mac Shell: CPP/>$


Code written:



string Cleanup(string Roman){
int count = 0;

printf("input: %s\n", Roman.c_str());

size_t w = Roman.find("VIV");
Roman.replace(w, std::string("VIV").length(), "IX");


/* size_t x = Roman.find("LIX");
Roman.replace(x, std::string("LIX").length(), "IL");

size_t y = Roman.find("VIV");
Roman.replace(y, std::string("VIV").length(), "IX");

size_t z = Roman.find("VIV");
Roman.replace(z, std::string("VIV").length(), "IX");*/

return Roman;
}


I have been doing some reading here:

http://www.cplusplus.com/reference/string/string/replace/


  • Does anyone see what I am doing wrong?

  • Am I making this way harder than it needs to be?


obe obe
Answer

When the string is not found Romand.find() returns string::npos, which equals (std::string::size_type)-1.

See here: http://www.cplusplus.com/reference/string/string/find/

Comments