By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
426,115 Members | 898 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 426,115 IT Pros & Developers. It's quick & easy.

help with user input into arrays

P: 15
hey ive been messing around with this program to take a user inputed number, put it into an array and then reverse the number. I also want it to omit unecessary 0's at the begging.

for example if the user inputs 100 the reverse shows 1, becuase with 001 the leading zeros are unecessary.

I finally did it a complicated way and was wondering if there is an easier way to get the user inputed number into the array, and prefferably into an int array not a char.
heres my code any help is greatly appreciated...

Expand|Select|Wrap|Line Numbers
  1.  
  2. #include <iostream>
  3.  
  4. void reverse(char input[]){
  5.  
  6.     int c=0;
  7.     for (int x=0; input[x]!='\0' ; x++)
  8.         c++;
  9.     while (true){
  10.         if (input[c-1] !='0'){    
  11.             for(c; c >= 0; c--)
  12.                 cout << input[c-1];
  13.  
  14.             cout << endl;
  15.             break;
  16.             }
  17.         else
  18.             c--;
  19.         }
  20. }
  21.  
  22. int main(void)
  23. {
  24.    char input[256];
  25.  
  26.     cout << "Please enter a postive integer: ";
  27.     cin.getline (input,256);
  28.  
  29.     reverse (input);
  30.  
  31.    return 0;
  32. }
  33.  
thanks

Rod
Nov 7 '06 #1
Share this Question
Share on Google+
1 Reply


Expert 100+
P: 1,510
you can use strlen() to get the number of character in the string and you can test for leading 0's in the while(), e.g.
Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <iomanip>
  3. using namespace std;
  4.  
  5. void reverse(char input[]){
  6.     int c=strlen(input)-1;
  7.     while (input[c] =='0') if (--c < 0) { cout << "0\n"; return; }
  8.     for(c; c >= 0; c--)
  9.             cout << input[c];
  10.     cout << endl;
  11. }
  12.  
  13. int main(void)
  14. {
  15.    char input[256];
  16.     cout << "Please enter a postive integer: ";
  17.     cin.getline (input,256);
  18.     reverse (input);
  19.    cin.get();cin.get();
  20.    return 0;
  21. }
  22.  
it will print a 0 for all 0000's input
Nov 7 '06 #2

Post your reply

Sign in to post your reply or Sign up for a free account.