This is a discussion on An algorithm about C/C++ within the C++ Programming forums, part of the General Programming Boards category; 1) How can i prevent user to enter a incorrect number. Put your code to the user input into a ...

1. 1) How can i prevent user to enter a incorrect number.
Put your code to the user input into a post checking loop (do while) and keep yelling at the user until they entire something that is valid.

I think i must declare four functions: transToBinary, transToDecimal, transToHexa, transToOcta
You can do it with one function, just pass the base to the function.

Is there anyone there who can solve this problem and help me to make this program
We are not in the buisness of writting homework here.

Other things I've noticed:
use tolower() or toupper() instead of the stacked case statements. While its legal its also fugly for this usage.
You need to get the number from the user as a string and not an int. You then have to convert the string into an int depending on the base.

2. ## Um, in my experience, one need not know how many numbers there are in the number...

I know this is true of base 10, but i'm not sure about the others every time.

You look at each number in turn:
1243

[PSUEDO]
Code:
```0 -> current number
10 -> base
Mark A
convert to decimal ( '1' ) -> new digit
( current number * base ) + new digit -> current number
Goto mark A and repeat for each character```
[/PSUEDO]

~Inquirer

3. Try this:

Code:
```#include <iostream.h>
#include <string.h>
#include <ctype.h>

int main() {
int number, base, i, j;
char b, input[50];
char num[]="0123456789abcdef";

do {
cout<<"\nBase? [d]ecimal, [b]inary, [o]ctal, [h]ex:";
cin>>b;
b=(char)tolower(b);

switch(b) {
case 'd': base=10; break;
case 'b': base=2; break;
case 'o': base=8; break;
case 'h': base=16; break;
default: base=0;
}
if(base==0) cout<<"\nplease input only d, b, o, or h.\n";
} while(base==0);

cout<<"\ninput ";
switch(base) {
case 2: cout<<"binary"; break;
case 8: cout<<"octal"; break;
case 10: cout<<"decimal"; break;
}
cout<<" number: ";
cin>>input;

number=0;
for(i=0; i<strlen(input); i++)
{
for(j=0; j<base; j++) {
if(num[j]==tolower(input[i])) {
number*=base;
number+=j;
break;
}
}
}

cout<<number;

return 0;
}```

4. moving to the c++ forum...

Page 2 of 2 First 12