Here is a program that I wrote to reverse any integer number enter into the program. It runs fine, but it keeps repeating. You type the integer in, it reverses it, then keeps saying "Enter Number You Wish to reverse: "... If you guys could help point out the mistake, that would be great. Thanks :D
The program appears to be working as intended. The while loop will repeat so long as the cin stream is not in a fail state. The intention here is that you enter some non-integer value - such as a letter of the alphabet in order to terminate the loop.
A more usual construction might be like this:
1 2 3 4 5 6 7 8
int num;
cout << "Enter Number You Wish to Reverse: ";
while (cin >> num)
{
cout << reverse (num) << endl;
cout << "Enter Number You Wish to Reverse: ";
}
Here it is more clear at line 4 that the body of the loop will be entered only if the user enters a valid integer. By the way, to clear the fail flag afterwards, perhaps to get some other input from the user, put
UPDATE. Here is my updated code. It performs well, however I'd still like it to exit after compiling once, if that makes sense. For example, I want it to exit after I find the reverse of a number one time. The code keeps repeating. What do I need to do. Also, it wont exit after line 28 executes. Yes I did some research and cant find the answers to my questions. Thanks guys.
Okay, so here is what I have. When num = 0 I want it to immediately exit, and not run the next function. So I dont want the while loop to run. What should I do. Here is another updated code.
You need to move the if (num == 0) check before the cout << reverse(num) << endl; line. (Otherwise reverse will get called and then it'll check if num is 0.)
/*
* Chapter 6 Programming Assignment
* CSIS 123 Programming Fundamentals
* Fall 2013
* This program will take an number input by the user, then reverse/flip
* the digit/s in that number.
*/
#include<iostream>
#include<stdlib.h>
usingnamespace std;
int reverse (int);//Function prototype
int main()
{
int num;
cout << "Enter Number You Wish to Reverse (Cannot = 0): ";
cin >> num;
cout << endl;
cout << reverse(num) << endl;
cout << endl;
system("Pause");
}
int reverse (int num)
{
int digit, reverseNumber = 0;
if (num == 0)//If the input number is equal to zero, the program will output the appropriate message, then exit.
{
cout << "**Invalid Input. Your Number Cannot = 0**" << endl;
cout << endl;
system("Pause");
exit(EXIT_FAILURE);//If zero is input, this will skip the remaining code (the while loop) and exit.
}
while (num != 0)//While the number is not zero, the input number will be reversed/flipped.
{
digit = num % 10;//Takes the last digit in the input number from right to left.
num /= 10;//This trims the last digit.
reverseNumber = reverseNumber * 10 + digit;//Finally, this is creates the flip/reverse with each digit.
}
cout << "Your Number Reversed Is: ";
return reverseNumber;
}