learner learner - 1 month ago 8
C++ Question

Unable to write integer to a string

Below is the code for converting integer to string,I am trying to not use C++ inbuilt functions for that but my code is not producing any output.

int main(){
int a;
string b;
cin>>a;
while(a){
b+=(a%10);
a/=10;
}

cout<<b;
return 0;
}


Input-


789




Expected Output-

987


but I am not getting any answer.
P.S- I have used all the required header-files in the code.

Answer Source

You cannot add an int to a string (or rather, you shouldn't in this case). You need to_string to convert the int to a string so that the += operator acts as concatenation:

#include <iostream>
#include <string>
using namespace std;
int main(){
    int a;
    string b;
    cin>>a;
    while(a){
        b+=std::to_string(a%10);
        a/=10;
    }
    cout<<b;
    return 0;
}

Demo


What was happening?

std::string has a operator+= that can allow for quick concatenation. You can concatenate another string or a character. Which version of concatenation is chosen via overload. When you tried string += int the char overload was selected (int converts to char) so random junk was appended to your string instead of what you intended.