c++: Problems with my code | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

c++: Problems with my code

#include <iostream> #include <string> int main() { std::string str; std::cin >> str; int count = 0; int i; for (i = 0; str[i] != '\0'; ++i) { count++; } if (count % 2 != 0) { str[i / 2] = ' '; int n = 0; for (int j = 0; j <= i; ++j) { if (str[j] != ' ') { str[n] = str[j]; n++; } } std::cout << str << std::endl; } else { std::cout << str << std::endl; } } In the above code, in line 15, if I write for (int j = 0; j < i; ++j) instead, the last character will be copied once again. For example, if I input "ab12c", the output will be "ab2cc". However, if I write the same code as the above-for (int j = 0; j <= i; ++j). I can get the output that I want. Why adding a "=" will copy the last character again? Even I am the one who writes this code, I still don't know why.XD

6th Dec 2019, 4:28 PM
汝風留名
汝風留名 - avatar
3 Answers
0
the <= is for less or equal. what happens when you enter a string with an odd length like 5 for example abcde. is the third char gets replaced by ' ' the string becomes ab' 'de with < in the loop j gets to 4 because that's less than 5 and never gets to 5, the str[4] =' e' it gets repeated because j=2 is skipped as it contains ' '. with <= j will get to 5,the length of the string. by the end str[5] doesn't contain any char as 5 chars in the str start from 0to4. that's why the last char is not repeated. I hope it makes sense :) you can add some std::cout to see the values of the variables at different stages of the executions. example : std::cout << j << std::endl; std::cout << str[j] << std::endl;
6th Dec 2019, 6:53 PM
Bahhaⵣ
Bahhaⵣ - avatar
0
#include <iostream> #include <string> int main() { std::string str; std::cin >> str; int count = 0; int i; for (i = 0; str[i] != '\0'; ++i) { count++; } if (count % 2 != 0) { str[i / 2] = ' '; std::cout << str <<std::endl; int n = 0; for (int j = 0; j <= i; ++j) { if (str[j] != ' ') { str[n] = str[j]; n++; std::cout << j <<" " << str[j] << std::endl; } } std::cout << str << std::endl; } else { std::cout << str << std::endl; } }
6th Dec 2019, 7:03 PM
Bahhaⵣ
Bahhaⵣ - avatar
0
OK👌 Thx
7th Dec 2019, 12:16 AM
汝風留名
汝風留名 - avatar