Huangwei Ding
Huangwei Ding

Reputation: 11

terminating with uncaught exception of type std::out_of_range: basic_string

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

//terminating with uncaught exception of type std::out_of_range: basic_string

Upvotes: 1

Views: 7623

Answers (1)

R Sahu
R Sahu

Reputation: 206747

Problems I see:

  1. You need to use s.length() instead of sizeof(s).
  2. You need to use index values starting at 0, not 1.
  3. You need to use i < ... instead of i <= ....

All of the above are in the for statement. Use:

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

If you are able to use a C++11 compiler, you can simplify that to:

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

And then, you are using

c = c + 4;

and

c = c - 26;

even though you have not initialized c. That causes undefined behavior. I am not able to suggest a fix for that since you have not explained what the program is supposed to do.

Upvotes: 2

Related Questions