gpt4 book ai didi

c++ - 在 C++ 中查找和替换越界

转载 作者:太空宇宙 更新时间:2023-11-03 10:25:00 25 4
gpt4 key购买 nike

我似乎遇到了一种我在 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/>$

编写的代码:

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;
}

我一直在这里阅读:

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

  • 有人看到我做错了什么吗?
  • 我是否让这种方式变得比需要的更难?

最佳答案

您需要检查并防止出现“未找到”情况。

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

关于c++ - 在 C++ 中查找和替换越界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39521054/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com