Hello, I am trying to write a program that will reverse the numbers inputted by the user. It doesn't seem to be having the desired outcome and I don't know why.

Here is the code I am using,

#include <iostream>
#include <conio.h>
#include <string>
#include <sstream>
using namespace std;

int n0,n1,n2,n3,n4;
string mystr;

int main ()
{
    string mystr;
    cout << "Please enter an interger value up to "
    "the length of five numbers: " << endl;
    getline (cin,mystr); // gets the number inputted from the user
    n0 = mystr[0]; 
    n1 = mystr[1];
    n2 = mystr[2];
    n3 = mystr[3];
    n4 = mystr[4];
// that puts each number into an accessible variable
    cout << n4;
    cout << n3;
    cout << n2;
    cout << n1;
    cout << n0;
// when the user inputs 12345, instead of 54321, it outputs 53,52,51,50,49
    _getch();
    return 0;
}

I was thinking that it would be easier to pull the numbers from an array, but I tried that and got the same thing. Also I don't see how using a string is better than an array.

Recommended Answers

All 2 Replies

cout is smart about types. If you try to print a char, it will be interpreted as a character rather than a small integer. If you copy that value into an int object and print that cout will no longer interpret it as a character. You're seeing the integer value of the characters rather than the character representation.

Try changing int n0,n1,n2,n3,n4; to char n0,n1,n2,n3,n4; .

Thank you, that did the trick. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.