Bugster
Bugster

Reputation: 1594

Algorithm to print the reversed number given by user?

I've written a small program in C++ that prompts the user for input, the user gives a number, then the computer displays the number reversed.

For example: 17 becomes 71. 123 becomes 321.

This is the program:

#include <iostream>
#include <string>  //for later use.
using namespace std;

int rev(int x)
{
    int r = 0;
    while(x)
    {
        r = (r*10) + (x%10);
        x = x/10;
    }
    return r;
}

int main()
{
    int nr;
    cout << "Give a number: ";
    cin >> nr;
    rev(nr);
    cout << nr; 
    return 0;
}

The final result of the program: prints the same number, function has no effect. What am I doing wrong? I tried several solutions but to no avail.

Upvotes: 3

Views: 2025

Answers (5)

Matthieu M.
Matthieu M.

Reputation: 299810

There is a std::reverse function in the STL, which works with collections.

#include <algorithm>
#include <iostream>
#include <string>

int main() {

  long int i = 0;
  do {
    std::cout << "Gimme a number: " << std::endl;
  } while (not (std::cin >> i)); // make sure it *is* a number

  std::string display = std::to_string(i); // C++11

  std::reverse(display.begin(), display.end());

  std::cout << display << "\n";
}

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490108

While probably not in the intended spirit, the simple answer is that if you're only going to display it in reverse, you can cheat and just work with a string:

std::string input;

std::cin >> input;

std::cout << std::string(input.rbegin(), input.rend());

Upvotes: 2

N_A
N_A

Reputation: 19897

You need to change rev(nr); to nr = rev(nr);

or alternately change your function to:

void rev(int& x)
{
    int r = 0;
    while(x)
    {
        r = (r*10) + (x%10);
        x = x/10;
    }
    x = r;
}

Upvotes: 7

Mario
Mario

Reputation: 36487

You're doing it right, but you're not grabbing your return value (the reversed value).

To solve this, just assign or print the return value:

cout << rev(nr);

or

nr = rev(nr);
cout << nr;

Upvotes: 4

Charles Salvia
Charles Salvia

Reputation: 53289

You're not actually using the value that rev returns. You're just using the value nr which you pass to rev, and since you don't pass by reference, rev isn't being affected locally.

What you want to say is:

int nr;
cout << "Give a number: ";
cin >> nr;
int result = rev(nr);
cout << result; 
return 0;

Upvotes: 1

Related Questions