find an error: | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

find an error:

this code swaps last and first letter of a word and adds "ay" at the end #include <iostream> #include <string> int main() { std::string input = "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"; int last = 0, first = 0; //input to declare enough space char r; std::getline(std::cin, input); for (int i = 0; i <= input.length(); i++) { if (input[i] == '\0') { last = i - 1; break; } } r = input[last]; input[first] = input[last]; //swaps first and last letter input[last] = r; input[last + 1] = 'a'; input[last + 2] = 'y'; //adds an ay at the end std::cout << input; }

1st Oct 2020, 7:15 PM
ItzNekS
ItzNekS - avatar
3 Answers
0
Instead loop, you can simply write like this last = input.length()-1; And r = input[last]; //last storing input[first] = input[last]; //again last storing in first, now last the first value.. input[last] = r; //last = last. Instead you need r = input[last]; input[last] = input[first]; input[first] = r;
1st Oct 2020, 7:31 PM
Jayakrishna 🇮🇳
0
thank you, now the code swaps last and first char, but adding "ay" still doesnt work nevermind, figured it out, changed it to input = input + "ay";
1st Oct 2020, 8:13 PM
ItzNekS
ItzNekS - avatar
0
Yes. Simply it works.. input+="ay"; Adding at index positions will not increasing string length.. Or You can do like this input += (input[last + 1] = 'a'); input += (input[last + 2] = 'y');
1st Oct 2020, 8:42 PM
Jayakrishna 🇮🇳