Is it possible to index integers in C++?

Started by
11 comments, last by Conner McCloud 17 years, 7 months ago
I made some improvements, I hope, to the program I did before and just for the heck of it I thought I'd post what changes I made.
(1)Got rid of my loose numbers by turning them into constants,
(2)Inserted an if-else statement to make sure the program recieved the right type of data,
(3)Used a while loop because I was sick of having to click run all the time
(4)Tried to improve the math portion like deadimp suggested
(5)Took out the static_cast since, as kylotan said, they weren't necessary

#include<iostream>

using namespace std;

int main()
{
int userNum;

const int INT_1000 = 1000;
const int INT_100 = 100;
const int INT_10 = 10;

char again = 'y';
while(again == 'y')
{
cout << "Please enter a positive four digit integer: ";
cin >> userNum;

if(userNum >= 1000 && userNum <= 9999)
{
cout << userNum/INT_1000 << endl;
cout << (userNum %= INT_1000)/INT_100 << endl;
cout << (userNum %= INT_100)/INT_10 << endl;
cout << userNum % INT_10 << endl;
}
else
cout << "Number is invalid.\n" << endl;

cout << "Do you want to try again? (y/n): ";
cin >> again;
cout << endl;
}

system("PAUSE");

return 0;
}
Advertisement
INT_1000 is an example of how not to get rid of loose constants.

:)

Here are some hints:
Write "convert int to std::string in base 10" as a function.
Write "convert base 10 std::string to int" as a function.
Write "get max and min ints for an N diget number in base 10" as a function (or two functions).

If you are keen, you could even write the above in a generic base.

This will make the only special numbers in your code "number of digets" and "base of digets" -- both of these numbers make sense without understanding the details of your algorithm, and if you change either (to reasonable values) your program continues to work.


...

Instead of "fakeing" user input by setting again to be 'y', try having a bool loop variable called something like "keep_getting_input_from_user". Or just loop while(true) and explicity break; out of the loop when the user asks you to quit.

Faking use input is a lie. There isn't any reason to lie to your program in this case -- it doesn't make your program any tighter, easier to read, etc. And lieing makes baby jesus cry. :)
Quote:Original post by dvail87
    char again = 'y';    while(again == 'y')    {        ...    }


Lookup 'do', it should work wonders here.

Your second draft is better than your first, although Yakk is correct to suggest that your constants are no better than what you had before.

Here's a thought for the next step, should you choose to keep plugging away at it: what happens if you reverse the process? Print '8024' as '4208.' Can you think of any simplifications for this case?

CM

*edit: removed unintentional pun.

This topic is closed to new replies.

Advertisement