+ 3

[CLOSED] Why am I getting this result?! Please help!

#include <iostream> #include <string> using namespace std; int main() { string userstr; cin >> userstr; cout << userstr << endl; char group[] = {'a', 'b', 'c', 'd','e', 'f', 'g', 'h', 'i', 'j','k', 'l', 'm', 'n', 'o', 'p','q', 'r', 's', 't', 'u', 'v','w', 'x', 'y', 'z', 'a', 'b', 'c', 'd','e', 'f', 'g', 'h', 'i', 'j','k', 'l', 'm', 'n', 'o', 'p','q', 'r', 's', 't', 'u', 'v','w', 'x', 'y', 'z'}; for(int n = 0; n < userstr.length(); n++) { for(int l = 26; l < 52; l++) { if(userstr[n] == group[l]) { userstr[n] = group[l - 1]; } }; }; cout << userstr; return 0; } If I input 'a' it gives me 'y' (when it should be giving 'z')! With all others it works fine, just not 'a'. Ex. Input: c Output: b

27th Jul 2019, 11:02 PM
UrBoyO
UrBoyO - avatar
6 Respostas
+ 6
Use break statement inside if block after assignment. What happens is that if you input a, the if condition is executed twice. First time when both userstr[n] = 'a' and group[n] = 'a'. After the execution of if block first user[n] = 'z' (z is assigned). But again when l gets equal of 51 so group[51] = 'z' and when the condition is checked i.e if(userstr[n] == group[n]) Since both have same character so the condition evaluates to true and userstr[n] is assigned 'y' for(int l = 26; l < 52; l++) { if(userstr[n] == group[l]) { userstr[n] = group[l - 1]; break; } };
28th Jul 2019, 1:09 AM
blACk sh4d0w
blACk sh4d0w - avatar
+ 3
Ian Moore Your welcome 😊
28th Jul 2019, 1:20 AM
blACk sh4d0w
blACk sh4d0w - avatar
+ 3
Ian Moore Once again your most welcome. Glad to see your code 😊
28th Jul 2019, 7:11 AM
blACk sh4d0w
blACk sh4d0w - avatar
+ 2
nAutAxH AhmAd I finished it! I gave you a quick shout-out in the comments 😀 https://code.sololearn.com/cZ8SP8W2MjFQ/?ref=app Once again, thank you for helping me fix a simple mistake I should've been able to see on my own.
28th Jul 2019, 1:57 AM
UrBoyO
UrBoyO - avatar
+ 1
nAutAxH AhmAd THANK YOU SO MUCH!! This means a lot more than you think! 😁
28th Jul 2019, 1:17 AM
UrBoyO
UrBoyO - avatar
+ 1
nAutAxH AhmAd I just tried it out and it works! Whoo-hoo!! 😅
28th Jul 2019, 1:21 AM
UrBoyO
UrBoyO - avatar