gpt4 book ai didi

c++ - 以 std::out_of_range: basic_string 类型的未捕获异常终止

转载 作者:行者123 更新时间:2023-11-30 03:35:09 25 4
gpt4 key购买 nike

#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
cin>>s;
int i;
char c;
for(i=1;i<=sizeof(s);i++){
if((s.at(i)>='a'&&s.at(i)<='z')||(s.at(i)>='A'&&s.at(i) <='Z')){
c=c+4;
if((s.at(i)>'Z'&&s.at(i)<'\136')||(s.at(i)>'z')){
c=c-26;
}
}
}
cout<<c;
return 0;
}

//以 std::out_of_range: basic_string 类型的未捕获异常终止

最佳答案

我看到的问题:

  1. 您需要使用 s.length()而不是 sizeof(s) .
  2. 您需要使用从 0 开始的索引值, 不是 1 .
  3. 您需要使用 i < ...而不是 i <= ... .

以上所有都在for中陈述。使用:

for(i=0; i < s.length(); i++){

如果您能够使用 C++11 编译器,您可以将其简化为:

for( auto ch : s ){
// Use ch instead of s.at(i) in the loop.
}

然后,你正在使用

c = c + 4;

c = c - 26;

即使你还没有初始化c .这会导致未定义的行为。我无法为此提出修复建议,因为您还没有解释该程序应该做什么。

关于c++ - 以 std::out_of_range: basic_string 类型的未捕获异常终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41456900/

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