在C++中使用find和replace超出界限

Rob*_*t J 1 c++

我似乎遇到了一个奇怪的情况,我不会在C++中.当我执行一个解析和替换字符串的函数(罗马数字).如果字符串不存在,我最终会超出界限:

终端输出:

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/>$ 
Run Code Online (Sandbox Code Playgroud)

代码编写:

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;
}
Run Code Online (Sandbox Code Playgroud)

我一直在这里读书:

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

  • 有谁看到我做错了什么?
  • 我这样做的方式比它需要的更难吗?

AJN*_*eld 5

您需要检查并防止"未找到"状态.

size_t w = Roman.find("VIV");
if (w != string::npos) {
    Roman.replace(w, string("VIV").length(), "IX");
}
Run Code Online (Sandbox Code Playgroud)