+ 2

Please help me in this

This is the question Write a program that takes a five-digit number from the user and Separate the digits and print with a space of three characters For example input 12345 Output 5. 4. 3. 2. 1. https://code.sololearn.com/cKz3lpAGzO28/?ref=app Whats the matter in this?

23rd Nov 2020, 1:01 PM
Jason
Jason - avatar
4 Answers
+ 5
Multiplying a character means multiplying its ASCII value. For a space, the operation 3 * ' ' means 3 * 32 = 96. Likewise, adding characters means adding their ASCII values. The lowest digit zero has an ASCII value of 48, followed by the other digits. Therefore, adding 96 results no matter which digit is given in a value bigger than 127, the largest value a signed character can represent. Thus, the value overflows, and you add characters with negative ASCII values to the output string, which have no proper console representation, hence the output. I don't think you need the second string. Just print the digits and spaces directly inside the loop, without using another buffer inbetween. Otherwise, you need to get rid of the multiplication and addition aspect. The only string operation that is defined as what you intuitively might assume it is, is string concatenation via the + operator, but only for C++ strings.
23rd Nov 2020, 1:31 PM
Shadow
Shadow - avatar
+ 2
It gives an error again
23rd Nov 2020, 1:39 PM
Jason
Jason - avatar
+ 2
If you are referring to the warning, that was there before as well, and is issued because you compare a signed integer to an unsigned integer in the loop condition. You can get rid of it by declaring 'i' with the size_t data type instead of int, which is usually the same type the length() method returns.
23rd Nov 2020, 1:47 PM
Shadow
Shadow - avatar
0
if you want to modify the string like the output then you can try this if you want to: #include <iostream> #include <string> #include <algorithm> std::string& processStr(std::string& s) { std::reverse(s.begin(), s.end()); std::string::iterator it = s.begin(); while (it != s.end()) { it = s.insert(it + 1, '.'); it = s.insert(it + 1, ' '); it = s.insert(it + 1, ' '); it = s.insert(it + 1, ' '); it++; } return s; } int main() { std::string in("12345"); std::cout << processStr(in) << '\n'; return 0; } https://code.sololearn.com/cM33bTkLnQX5/?ref=app
23rd Nov 2020, 2:43 PM
Flash