代碼有問題。顯示錯誤"std::out_of_range at memory location"。在除錯程序中。代碼的任務是找到文本中的所有字母“A”并將其洗掉。**С 代碼:**
#include <iostream>
#include <string>
using namespace std;
int main()
{
string a;
getline(cin, a);
int n = 0;
do {
n = a.find('a',1);
cout << n;
a.erase(n, 0);
cout << a;
} while (n != -1);
cout << a;
}
我試圖將 int 更改為 double,但程式無法正常作業。但是,錯誤消失了
uj5u.com熱心網友回復:
這個 do-while 回圈有兩個問題
do {
n = a.find('a',1);
cout << n;
a.erase(n, 0);
cout << a;
} while (n != -1);
第一個是您開始從位置 1 而不是位置 0 開始搜索字母“a”。
第二個是如果找不到字母“a”,則 n 等于 std::string::npos 并且您在擦除呼叫中使用此值。在呼叫成員函式擦除之前,您需要檢查 n 是否不等于 std::string::npos。
無論如何,擦除的呼叫都是不正確的。
而不是 do-while 回圈,最好使用 for 回圈。例如
for ( std::string::size_type n; ( n = a.find( 'a' ) ) != std::string::npos; )
{
std::cout << n;
a.erase(n, 1 );
std::cout << a << '\n';
}
此外,您應該將變數 n 宣告為具有 std::string::size_type 型別。
正如@Ted Lyngmo評論中所寫,如果您的編譯器支持 C 20,那么您可以使用erase為標準容器定義的標準 C 函式,例如
std::erase( a, 'a' );
洗掉字串中所有出現的字母'a'。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/450394.html
