Double output problem in string

Hey, so I'm writing a code for my Programming 1 class and its supposed to get a string(one word) from the user and a key, and then update and output the new string. So for example if the input is QUIZ and the key is 7, the output should be XBPG. For some reason my code is outputting double X and P for this string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <cstring>
using namespace std;
int main() {
    string input;
    int i, size, key;
    
    cout<<"Enter a string: ";
    cin>>input;
    
    size = input.length();
   
    cout<<"Enter the key: ";
    cin>>key;
    
    cout<<"The new text is: ";
    if(key>1 && key<26){
        for(i=0;i<size;i++){
            if((input[i]+key)<='Z'){
                input[i]=input[i]+key;
                cout<<input[i];
            }
            else
                input[i]= 64 + ((input[i]+key) - 'Z');
                cout<<input[i];
        }
    }
    cout<<endl; 
        
    return 0;
}


My output:

Enter a string: QUIZ
Enter the key: 7
The new text is: XXBPPG
Program ended with exit code: 0
Last edited on
Here,you have primarily two problems:-

1)Your else block on line 23 is not proper,as there should be brackets around the block for the correct output to come.

2)You want to convert an int to char and a char to int,but you dont use correct casts and think the compiler will do the work for you.That type of implicit casts are risky to deal with,often heralding in cases where the output is not tht which is required.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <string>
using namespace std;
int main() {
    string input;
    int i, size, key;
    
    cout<<"Enter a string: ";
    cin>>input;
    
    size = input.length();
   
    cout<<"Enter the key: ";
    cin>>key;
    
    cout<<"The new text is: ";
    if(key>1 && key<26){
        for(i=0;i<size;i++){
            if(static_cast<char>(static_cast<int>(input[i])+key)<='Z'){
                input[i]=static_cast<char>(static_cast<int>(input[i])+key);
                cout<<input[i];
            }
            else
             {
                input[i]= static_cast<char>(64 + static_cast<int>(input[i])+key - static_cast<int>('Z'));
                cout<<input[i];
             }
        }
    }
    cout<<endl; 
        
    return 0;
}


Heres the correct code. Hope you learn.
Also read this:
http://stackoverflow.com/questions/103512/why-use-static-castintx-instead-of-intx

And this:
http://stackoverflow.com/questions/332030/when-should-static-cast-dynamic-cast-const-cast-and-reinterpret-cast-be-used
Ohh I totally forgot the brackets thanks! And my bad, I assumed it would automatically switch back to char because the array was declared as a string data type.
Topic archived. No new replies allowed.