[英]What is the following error doing? I do not see any error with the bounds
該代碼具有頭文件、實現文件和主文件。 它應該增加字符串中所有字符的 ASCII 值,然后返回與該 ASCII 值關聯的字符值。
有問題的代碼如下:
for(int i = 0; i < sizeof(letters); i++)
{
if ((int)letters.at(i) >= (int)'a' && (int)letters.at(i) <= (int)'z')
{
letters.at(i) = (((letters.at(i) - 'a') + 1) % 26 + 'a');
}
else if ((int)letters.at(i) >= (int)'A' && (int)letters.at(i) <= (int)'Z')
{
letters.at(i) = (((letters.at(i) - 'a') + 1) % 26 + 'A');
}
}
HomeworkNine.exe 中 0x750A3DB2 處未處理的異常:Microsoft C++ 異常:內存位置 0x00EFF7E8 處的 std::out_of_range。 發生了
我沒有看到越界在哪里,因為我認為模數會解決這個問題。
sizeof(letters)
僅當letters
是一個普通的char
數組時才是正確的,因為普通數組沒有at
成員函數,所以不能這樣。 C++ 標准庫中的at
成員函數與size()
比較隨機訪問序列,如果索引不小於size()
則拋出std::out_of_range
。 您需要用letters.size()
替換sizeof(letters)
letters.size()
。
請注意,大寫分支有一個錯誤,即-'a'
然后是+'A'
。
這些強制類型int
因為編譯器他們為你(或者是不必要的unsigned
,如果char
是你的平台上無符號)。 內置算術運算符和比較僅適用於int
或更大的類型,請參閱積分提升。
替代 C++11 版本:
std::string letters("abc..zABC..Z");
for(auto& c : letters) {
if(std::isalpha(c))
c += std::tolower(c) != 'z' ? 1 : ('a' - 'z');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.