-2

The code below works for reversing a number with a zero as such

Enter a positive integer: 650
The number 650 reversed is: 056

but not for this

Enter a positive integer: 045
The number 45 reversed is: 54

I was looking for 540 not 54

I ran across this previous question:

Is it possible to store a leading zero in an int?

Is formatting still the answer to fix my code- if so where to add it. Or it is a different problem. Again thanks fo the insight

#include <iostream>
#include <iomanip>

using namespace std;

int main() {

 int number, disp_num, c_num, check_num =0, count = 0, rev_count=0, reverse = 0;


cout << "Enter a positive integer: ";
cin>> number; 

while(number < 0){
    cout << "That number is not positive. Enter a positive integer: ";
    cin >> number;
}

disp_num = number;



  for( ; number!= 0 ; )
  {
  reverse = reverse * 10;
  reverse = reverse + number%10;
  number = number/10;
  count += 1;
  }

 c_num = reverse;

 for( ; c_num!= 0 ; )
{
   check_num = check_num * 10;
   check_num = check_num + c_num%10;
   c_num = c_num/10;
   rev_count += 1;
 }

if (rev_count != count){
    cout << "The number " << disp_num << " reversed is: ";
    for (int i = 0; i < (count - rev_count); i++){
        cout << "0";
    }
    cout << reverse << endl;
}

else{
cout<< "The number " << disp_num << " reversed is: " <<reverse << endl;
}
return 0;
Community
  • 1
  • 1
user1560265
  • 57
  • 1
  • 2
  • 8

2 Answers2

0

As Pete Becker said, work with strings, not with the actual value. There is no way to reverse a number and keep the leading zeros in a simple int or any primitive. You'd need some type of structure to keep track of how many leading zeros there are.

#include <string>
#include <sstream>
#include <iostream>

std::string reverse(unsigned num) {
    std::stringstream ss;
    for(; num > 0; num /= 10)
        ss << num % 10;
    return ss.str();
}

int main(){
    std::cout << reverse(12340) << std::endl;  // prints "04321"
    std::cin.get();
    return 0;
}
Goodies
  • 4,439
  • 3
  • 31
  • 57
0

there's no way to get a value as with zero at leftmost because the compiler ignores it. the solution is to get your input as a string not as a integer value. if you then want the input as an int then call some conversion functions like atoi()...

consider this:

#include <iostream>
#include <string>
using namespace std;


int main()
{

    typedef string str;

    str strValue, strTmp;;
    char c;

    cout << "Enter value: ";

    while('\n' != cin.peek() && isdigit(cin.peek()))
    {
        c = cin.get();
        strValue += c;
    }

    cout << "strValue: " << strValue << endl;

    for(int i(strValue.length() - 1); i >= 0; i--)
        strTmp += strValue[i];

    strValue = strTmp;

    cout << "strValue: " << strValue << endl;


    return 0;
}
Raindrop7
  • 3,889
  • 3
  • 16
  • 27