Home > Software engineering >  Convert number into character
Convert number into character

Time:11-04

I want an reverse integer value.

the code

int number = 123, num1, num2, num3;
num1 = number / 100;
num2 = number % 100 / 10;
num3 = number % 10;

static_cast<char>(num1, num2, num3);

cout << num3   num2   num1 << endl;

the result is 6.. (I wanted '321' to come out.)

what is the problem with my code?

CodePudding user response:

Problem:

Even if you transform an int to a char using static_cast<char>, it will keep its value. Additionally, that's not the way you call static_cast<char>.

Solution:

If you just want to print them using your method, you don't even have to convert the numbers to char. Just print them taking advantage of the << operator.

#include <iostream>

int main(){
    int number = 123, num1, num2, num3;
    num1 = number / 100;
    num2 = number % 100 / 10;
    num3 = number % 10;
    std::cout << num3 << num2 << num1 << std::endl;
}

However, this is will only work for numbers between 100 and 999.

A much better solution would be to transform the number to the std::string and reverse it with std::reverse from the <algorithm> header.

#include <iostream>
#include <algorithm>

int main(){
    int number = 123;
    std::string str = std::to_string(number);
    std::reverse(str.begin(),str.end());
    std::cout << str << std::endl;
}

Then, if you want to get the reversed number as an integer instead of printing it, you can use std::stoi.

#include <iostream>
#include <algorithm>

int main(){
    int number = 123;
    std::string str = std::to_string(number);
    std::reverse(str.begin(),str.end());
    int reversed_number = std::stoi(str);
    std::cout << reversed_number << std::endl;
}

Note that this won't work and will throw an exception for negative numbers because of the leading '-'.

CodePudding user response:

Wrong operator ! Instead of " " : use "<<" to output concatenation of the 3 integers-strings No static casting.needed

#include <iostream>
int main(int argc, char* argv [])
{
  int number = 123, num1, num2, num3;
  num1 = number / 100;
  num2 = number % 100 / 10;
  num3 = number % 10;
  //static_cast<char>(num1, num2, num3);
  std::cout << num3 << num2 << num1 << std::endl;
}
  •  Tags:  
  • c
  • Related