1
#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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Maybe you could also show him a range based for solution, which would take care mistakes 1,2 and 3.
Thank you so much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.