I need to develop a program that converts a positive number from a given base to another base ranging from 2 to 10. I was initiatially thinking case statements but is there another way? Heres my start:

#include<stdio.h>

int main(void)

{
int num;
int sourcebase;
int targetbase;

//Get num and source base

do {
printf("Enter a positive number/n");
scanf_s("%d",&num);
Prinf("Enter the base of that number");
scan_s("%d" &sourcebase);
if((num<2)||(num>10)){
printf "You number is invalid!!!!!!!/n/n");
}
}
while(((num<2)||(num>10));
if (sourcebase==2)

Note the free(result) ... it might not be needed depending on your implementation of to_base_x, but we'll take care of that later ... for now try to come up with some code ...

0

wkellyaAuthor Commented:

ok but first why are we converting to and from a string? And how do I see that the users source base and destination base are in the range?

0

Thereâ€™s a high demand for IT security experts and network administrators who can safeguard the data that individuals, corporations, and governments rely on every day. Pursue your B.S. in Network Operations and Security and gain the credentials you need for this high-growth field.

>> ok but first why are we converting to and from a string?
You need to have a format that is able to represent numbers in different bases. A string can easily do that.

>> And how do I see that the users source base and destination base are in the range?
In the code you posted, you checked whether num was in the range 2 to 10 ... so, you know how to check whether a number is in a certain range. I don't understand your question ...

Just to make things clearer for you, I'll give you an example of how the program could work :

Enter a positive number : 120
Enter the base of that number (2 to 10) : 3
Enter the target base (2 to 10) : 5
The number in the target base is : 30

The user wanted to convert the base 3 number 120 (= 15 in base 10) to base 5. The result is 30 :

so you're saying to convert the number to decimal first? Doesn't that mean that each number in 120 will have to be multiplied by 3 raised to 0 ,1 and 2? how will I do that? This is confusing

Ok,I know how base conversionsion works what i'm asking is how will I represent this procedure in the function for example 1x4^2+2x4^1+3x4^0=27. I was thinking of incrementing the raised power with a for statement. if this is what u mean.
//where i is the raised power
for (i=0,i>0,++i)

>> I was thinking of incrementing the raised power with a for statement.
That's a good approach.

btw, you can get a given character from a string using num_str[i].
And another thing that might be handy is : subtract '0' from a character between '0' and '9' to get the actual value of the digit.

eg. :

num_str = "123"
num_str[2] - '0' = '3' - '0' = 3

0

wkellyaAuthor Commented:

heres what I've done but i can't get out of myloop and and getting some data type related warnings any suggestions?

long double sourcebase;
int targetbase;
int tmp_number;
int* new_number = NULL;

do {
printf("Enter a positive number\n");
scanf_s("%d",&tmp_number);
printf("Enter the base of that number\n");
scanf_s("%d", &sourcebase);
printf("Enter the destination base");
scanf_s("%d",&targetbase);
if((sourcebase<2)||(sourcebase>10)){
printf ("You number is invalid!!!!!!!\n\n");
}

}
while( tmp_number );
int i=0;
int decimal=0;
{
decimal += (tmp_number % 10) * pow( sourcebase, i ) ;
tmp_number /= 10 ;
++i ;
}

And also since there is no reason to make it a double.

2) The do-loop will go on untill you give a 0 as tmp_number :

while( tmp_number );

3) This can't be right :

scanf_s("%d",&tmp_number);

You're reading the number as a DECIMAL (base 10) integer, while that's not necessarily the case. Remember that the base of this number is sourcebase.
I told you earlier that it's a good idea to read the number as a string instead ...

>> I guess I basically have to start over from scratch
No, just go over my points 1 at a time, and modify your code. Then post it here again.

0

wkellyaAuthor Commented:

ok i'll do what i can, thanks by the way you're being very patient. btw Num has to be an integer Can I declare as an integer and then convert to a string while reading in?

It doesn't HAVE to be an int. It can be a string representing an integer.

With scanf, there's only 2 ways to read an integer : decimal (base 10) and hexadecimal (base 16). Any other base CANNOT be read in as an integer using scanf. The easiest way to get around that limitation is to read it as a string, and then convert it to an int.

0

wkellyaAuthor Commented:

I started over doing this the best i could to be completely honest I got some of my previous attempt from someone and i think it threw me off. However this is my honest attempt now so be gentle

int sourcebase=0;
int targetbase=0;
char num[50];
int length=0;
int decimal=0;
int new_number=0;

//Get user info

do{
printf("Enter a positive number:");
scanf_s("%s", &num);//wont go any further i'm thinking its the way i read it in
printf("Enter the base of that number:");
scanf_s("%d", &sourcebase);
printf("Enter your target base");
scanf_s("%d", &targetbase);
if ((sourcebase<2||sourcebase>10)||(targetbase<2||targetbase>10)){
printf("Error your bases are out of range!!!/n/n");

}
} while ((sourcebase<2||sourcebase>10)||(targetbase<2||targetbase>10));

length=strlen(num);

for (int i=0;i<length;i++){

int j=0;
decimal=num[i] * pow( (float)sourcebase, j ) ;//pow won't except two int arguments
j++;
}
new_number=decimal % targetbase;
printf("Your number is:%d",new_number);

return 0;
}
ps this is due tomorrow so any major changes i can make are welcome

>> scanf_s("%s", &num);//wont go any further i'm thinking its the way i read it in
When using scanf_s, you need to specify the length of the string too :

scanf_s("%s", num, 49);

>> for (int i=0;i<length;i++){
Instead of counting up, you'll want to count down (you want to start from the last digit !)

>> decimal=num[i] * pow( (float)sourcebase, j ) ;
A few things here :
(a) you shouldn't use num[i] here, as that will have a value between 0x30 and 0x39 (ASCII values for '0' and '9'). Use (num[i] - '0') instead !
(b) this is a good start, but you're re-assigning to decimal over and over again, while you want to add to it ! Think about what happens. I'm not giving too much away on purpose since you've already proven that you know how to convert between bases - you just need to apply that knowledge here !

>> new_number=decimal % targetbase;
This is not sufficient. You'll have to do something similar as the previous loop, but the other way around.

>> ps this is due tomorrow so any major changes i can make are welcome
I'll stick around for a while ... so post your changes here ...

Another hint once you've got everything working : validate that the num string the user entered contains ONLY digits before using it.

should not be inside the loop, or you reset the value to 0 for every iteration !

0

wkellyaAuthor Commented:

int main(void)
{
//initialization section

int sourcebase=0;
int targetbase=0;
char num[50]; //is 50 a suffiencient length for char num
int length=0;
int decimal=0;
int new_number=0;
int j=0;

//Get user info

do{
printf("Enter a positive number:");
scanf_s("%s", num, 49);
printf("Enter the base of that number:");
scanf_s("%d", &sourcebase);
printf("Enter your target base:");
scanf_s("%d", &targetbase);//nothing happens after here
if ((sourcebase<2||sourcebase>10)||(targetbase<2||targetbase>10)){
printf("Error your bases are out of range!!!/n/n");

}
} while ((sourcebase<2||sourcebase>10)||(targetbase<2||targetbase>10));

>> char num[50]; //is 50 a suffiencient length for char num
more than enough ... an int can only hold 32 binary digits, so that's the max.

>> for (int i=0;i<length;++i){
As I said earlier : you don't want to count up, but down. The last digit has to be treated first.

>> for (int k=0;k<length;--k)
This loop will go on for a LOOONG time (untill k underflows) : you start with k = 0, and on each iteration you subtract one (so k = 0, -1, -2, ...). But you go on for as long as k < length, and every negative integer is smaller than length.
So, this is not what you want.

>> // I don't understand u mean by opposite should new num be ana array
After the first for loop, you have an integer representing the number the user gave.
Try adding a print just after the first loop :

printf("The intermediary state is :%d\n", decimal);

And check whether it's the same as the one the user entered (but in base 10 this time !).

Now, you have to convert that integer to the targetbase. For that you can use a combination of % and /

>> //Should i validate by sendin it though a loop before printing
I don't know what you mean.

0

wkellyaAuthor Commented:

>> for (int k=0;k<length;--k)
This loop will go on for a LOOONG time (untill k underflows) : you start with k = 0, and on each iteration you subtract one (so k = 0, -1, -2, ...). But you go on for as long as k < length, and every negative integer is smaller than length.
So, this is not what you want
So increment k?

Another hint once you've got everything working : validate that the num string the user entered contains ONLY digits before using it.
That why I asked about the loop

I'm stuck, it simply will not work pass a certain point. Thanks for all your help tho I guess I'll just turn in what i've done and hope to get a few points for trying.

>> So increment k?
For example, but it depends how you're gonna do that part.

>> That why I asked about the loop
I suggest to get it working first - then you can add the check. Btw, that check should happen right after you read the number !

>> I'm stuck, it simply will not work pass a certain point. Thanks for all your help tho I guess I'll just turn in what i've done and hope to get a few points for trying.
Don't give up. Show me your current code, and tell me where you're stuck ...

int sourcebase=0;
int targetbase=0;
char num[50];
int length=0;
int decimal=0;
int new_number=0;
int j=0;

//Get user info

do{
system("cls");
printf("Enter a positive number:");
scanf_s("%s", num, 49);

length=strlen(num);

for(int j=0;j<length;j++)//this to check if it is a positive number but thr loop contiinues without error
if (num[j]<0){
printf("Error number cannot be less than zero");
system("pause");
}
printf("Enter the base of that number:");
scanf_s("%d", &sourcebase);
printf("Enter your target base:");
scanf_s("%d", &targetbase); //After it gets here it tells me theres astackoverflow exception

if ((sourcebase<2||sourcebase>10)||(targetbase<2||targetbase>10)){
printf("Error your bases are out of range!!!\n\n");
system("pause");

}
} while ((sourcebase<2||sourcebase>10)||(targetbase<2||targetbase>10)||(num[j]<0));

length=strlen(num);

for (int i=0;i<length;++i){

decimal+= (num[i] - '0') * pow( (float)sourcebase, j ) ;
j++;
printf("%d",decimal);//This is to check if the number is really in decimal (its not)
}
for (int k=0;k<length;++k)

new_number=decimal % targetbase;

printf("Your number is:%d",new_number);//(the only out put i get is 2)

>> if (num[j]<0){
Every ASCII character is positive !!!
What you want to check for is that all characters in the string are between '0' and sourcebase.
So, make this :

Make sure that you read in sourcebase BEFORE this check, and that sourcebase is maximum 10 !!!

>> } while ((sourcebase<2||sourcebase>10)||(targetbase<2||targetbase>10)||(num[j]<0));
This will not do what you think, as num[j] will point to the '\0' at the end of the string

It's a better idea to make use of continue and break in the while loop :
1) continue : ends the current iteration, and goes to the next (do this when you notice a problem)
2) break : ends the loop (do this when everything is OK, and you've got all data)
That way you can use this :

} while (1);

>> length=strlen(num);
You've already done this inside the while loop - no need to do it again.

>> for (int i=0;i<length;++i){
You're still not starting from the last digit. You have to count DOWN from (length - 1) to 0 as I said earlier. That's why you get this :
>> //This is to check if the number is really in decimal (its not)

>> new_number=decimal % targetbase;
You need to do a bit more than that to convert from base 10 to the target base. How would you do it manually ?

>> This is frustrating
It shouldn't be. Just read my comments carefully, and try to make the modifications one at a time. You'll get there !!
And always try to keep in mind what is happening, and what you want to do !

0

wkellyaAuthor Commented:

Every ASCII character is positive !!!
What you want to check for is that all characters in the string are between '0' and sourcebase.
I included the check because it was specified that num was supposed to be positive like if the user entered -120 base whatever but i don't think it is necessar so i'll take it out

When you say count down is this wha tu mean?
for(int i=0;i,(length-1);i++){//Still not working

>> new_number=decimal % targetbase;
You need to do a bit more than that to convert from base 10 to the target base. How would you do it manually ?
I am thinking that I would divide out by the targetbase until i get to zero but i need a way to store the running remainders in memory perhaps another damn array can i work around this?

>> I included the check because it was specified that num was supposed to be positive like if the user entered -120 base whatever but i don't think it is necessar so i'll take it out
I understand why you did it, but the way you try it doesn't work. You're testing every character for negativity - and as I said, every ASCII character is positive, no matter if the whole string represents a negative number.
If you use the test I gave you in my previous post, it will also give an error when the given number is negative (ie. it contains the character '-') !!

>> When you say count down is this wha tu mean?
>> for(int i=0;i,(length-1);i++){//Still not working
No.
Counting up is : 0, 1, 2, ..., length-1
Counting down is : length-1, ..., 2, 1, 0

To do that with a for loop, you have to get three things :
1) initial value : i = length - 1
2) loop condition : i >= 0
3) in- or decrement : --i

Combine this to get :

for (i = length - 1; i >= 0; --i) { }

>> I am thinking that I would divide out by the targetbase until i get to zero but i need a way to store the running remainders in memory perhaps another damn array can i work around this?
There's a much easier way. I'll show you how I convert the base 10 number 154 to base 5 :

num = 154

next digit of new_num = (num % 5) = 4
num = num / 5 = 30
(new_num is now = 4)

next digit of new_num = (num % 5) = 0
num = num / 5 = 6
(new_num is now = 04)

next digit of new_num = (num % 5) = 1
num = num / 5 = 1
(new_num is now = 104)

next digit of new_num = (num % 5) = 1
num = num / 5 = 0
(new_num is now = 1104)

STOP because num is = 0

Do you see a pattern ? Can you code that ? Notice that you'll need to store new_num in a string too !!

int sourcebase=0;
int targetbase=0;
char num[50];
int length=0;
int decimal=0;
int new_number[50];
int j=0;
int newnum=0;

//Get user info

do{
system("cls");
printf("Enter a positive number:");
scanf_s("%s", num, 49);

length=strlen(num);

for(int j=0;j<length;j++)
if ((num[j] < '0') || (num[j] >= sourcebase + '0')){//gives me an error a couple of time and then continues
printf("Error number cannot be less than zero");
system("pause");
}
printf("Enter the base of that number:");
scanf_s("%d", &sourcebase);
printf("Enter your target base:");
scanf_s("%d", &targetbase);

if ((sourcebase<2||sourcebase>10)||(targetbase<2||targetbase>10)){
printf("Error your bases are out of range!!!\n\n");
system("pause");

}
} while ((sourcebase<2||sourcebase>10)||(targetbase<2||targetbase>10));
//do i break here?

for(int i=0;i<(length-1);i++){

decimal+= (num[i] - '0') * pow( (float)sourcebase, j ) ;
j++;
printf("%d",decimal);//still not working
}
for (int k=0;k<length;++k)//heres my crack at it

>> if ((num[j] < '0') || (num[j] >= sourcebase + '0')){//gives me an error a couple of time and then continues
That's because you have to read in sourcebase BEFORE this line !!!

So :
1) read sourcebase
2) check that sourcebase is between 2 and 10
3) read num
4) check that num is a valid number
5) read targetbase
6) check that targetbase is between 2 and 10

With regards to break and continue :

do {
// read value
if (errorcondition) {
// print error message
continue;
}
// do something else
break;
} while (1);

The continue in the above code, will skip the rest of the loop, and go back to the "do", and start over.
The break will exit the loop (put this at the end when you're sure that everything was read in fine !!).

>> for(int i=0;i<(length-1);i++){
Check my earlier comment about counting DOWN instead of UP.

>> for (int k=0;k<length;++k)//heres my crack at it
drop this line

>> while(decimal!=0){
>> newnum=decimal%targetbase;
>> decimal=decimal/targetbase;
>> new_number[k]=newnum;
>> }
This is a very good start ! The only problem is that k will not be incremented !
And you have to make sure that you fill in the LAST digit first (remember, a number starts from the back !!).
And also make sure that you fill in the characters '0' through '9' instead of just the values 0 through 9. So, use ('0' + newnum) instead.

>> //still not working but i can see light at the end of the tunnel
Yep, it's coming :) Just go over my comments carefully, and try to understand them. If there is something you don't understand, then PLEASE ask me, and I'll be glad to explain it. You HAVE to understand the code you're writing, or you're gonna have a difficult time getting it to work !!

int sourcebase=0;
int targetbase=0;
char num[50];
int length=0;
int decimal=0;
char new_number[50];
int j=0;
int newnum=0;

//Get user info

do{
system("cls");
printf("Enter a source base:");
scanf_s("%d", &sourcebase);

if((sourcebase<2||sourcebase>10)){
printf("Error your sourcebase is out of range!!!\n\n");
system("pause");
}continue;//this is a strange one , when i press enter the number gets erased
printf("Enter a positive number:");
scanf_s("%s", num, 49);

length=strlen(num);

for(int j=0;j<length;j++){
if ((num[j] < '0') || (num[j] >= sourcebase + '0')){
printf("Error number cannot be less than zero");
system("pause");
}continue;
}
printf("Enter your target base:");
scanf_s("%d", &targetbase);

if ((targetbase<2||targetbase>10)){
printf("Error your targetbase is out of range!!!\n\n");
system("pause");
}continue;
break;
} while (1);//So while (1) is the condition that everthing is true?

// The only problem is that k will not be incremented !
//why not?
//And you have to make sure that you fill in the LAST digit first (remember, a number starts from the back !!).
//I don't understan what you mean by that.How?
//And also make sure that you fill in the characters '0' through '9' instead of just the values 0 through 9. So, use ('0' + newnum) instead.
//so new_number[k]=('0' + newnum);

>> }continue;//this is a strange one , when i press enter the number gets erased
You need to put it INSIDE the if block of course. It can only be executed if a problem occurs.
The same applies to the other continue's !!!

>> for(int j=0;j<length;j++){
>> if ((num[j] < '0') || (num[j] >= sourcebase + '0')){
>> printf("Error number cannot be less than zero");
>> system("pause");
>> }continue;
>> }
In this case, the continue will apply to the for loop, not to the while loop !!
So, you have to do it slightly differently :

for(int j=0;j<length;j++){
if ((num[j] < '0') || (num[j] >= sourcebase + '0')){
printf("Error number cannot be less than zero");
system("pause");
break; // if we notice something wrong in the string we jump out of the for loop ...
}
}
if (j < length) continue; // if we didn't reach the end of the string, that means a problem was encountered, so we continue ...

>> } while (1);//So while (1) is the condition that everthing is true?
Indeed. So, the loop will go on untill the break is reached which will stop the loop. And the break is only reached when all entered values are valid.

>> for (int k=0;k<length;++k)//drop which line?
This line :) You don't need this for statement !!

>> // The only problem is that k will not be incremented !
>> //why not?
Because you never do it.

>> //And you have to make sure that you fill in the LAST digit first (remember, a number starts from the back !!).
>> //I don't understan what you mean by that.How?
Check my earlier example again :

I'll show you how I convert the base 10 number 154 to base 5 :

num = 154

next digit of new_num = (num % 5) = 4
num = num / 5 = 30
(new_num is now = 4)

next digit of new_num = (num % 5) = 0
num = num / 5 = 6
(new_num is now = 04)

next digit of new_num = (num % 5) = 1
num = num / 5 = 1
(new_num is now = 104)

next digit of new_num = (num % 5) = 1
num = num / 5 = 0
(new_num is now = 1104)

STOP because num is = 0

Do you notice how I fill in the LAST digit (4) first, then the next to last (0), then the second (1), and finally the first (1). Do you understand why I do it that way ?

>> //so new_number[k]=('0' + newnum);
Yes. Now all you have to do is make sure that k has the correct value.

>> printf("Your number is:%d",new_number);
You'll have to change this too, because new_number is a string and not an integer.

0

wkellyaAuthor Commented:

for(int j=0;j<length;j++){
if ((num[j] < '0') || (num[j] >= sourcebase + '0')){
printf("Error number cannot be less than zero");
system("pause");
break;
}
}
if (num[j] < length){continue;//error definition from the for loop is ignored; the definition from the enclosing scope is used
}

while(decimal!=0){

newnum=decimal%targetbase;
decimal=decimal/targetbase;
new_number[k]=newnum; //How do I get the new num values in the array so it reads up if I dont use a for statement? I'm not very good at manipulating arrays so i try to avoid them

printf("Your number is:%c",new_number);
//is this how we print it?

>> if (num[j] < length){continue;
Compare this with what I wrote in my last post - there's an important difference !

>> new_number[k]=newnum; //How do I get the new num values in the array so it reads up if I dont use a for statement?
You're already in a loop : the while loop !

>> I'm not very good at manipulating arrays so i try to avoid them
You will have to learn though :) It's not very difficult - you just have to think of an array as several elements stored one after the other. And you can easily access them by their index.

>> printf("Your number is:%c",new_number);
>> //is this how we print it?
%c is for one character. We want to print a whole string, so we use %s

0

wkellyaAuthor Commented:

do{
system("cls");
printf("Enter a source base:");
scanf_s("%d", &sourcebase);

if((sourcebase<2||sourcebase>10)){
printf("Error your sourcebase is out of range!!!\n\n");
system("pause");
continue;
}
printf("Enter a positive number:");
scanf_s("%s", num, 49);

length=strlen(num);

for(int j=0;j<length;j++){
if ((num[j] < '0') || (num[j] >= sourcebase + '0')){
printf("Error number cannot be less than zero");
system("pause");
break;
}
}
if (j < length) continue;//still starting over what am i doing wrong?

printf("Enter your target base:");
scanf_s("%d", &targetbase);

if ((targetbase<2||targetbase>10)){
printf("Error your targetbase is out of range!!!\n\n");
system("pause");
}
break;
} while (1);

>> What is the complete output you get ?
>> using 123 base 4 j=3
I meant the complete output, starting with :

Enter a source base:
...

>> so k should be initialized k=-1?
If you initialize k to -1, you're gonna count down like this :

-1, -2, -3, ...

That's not what you want either.

You want to index into the array. The indexes of the array go from 0 to 48. So you NEVER want a negative number !
You have to determine the length of the resulting number in the targetbase, and start from that index !!

0

wkellyaAuthor Commented:

update I added a break after the target base was read in

length=strlen(number);

for(int i=0;i<length;i++){
if((number[i]<'0')||(number[i]>=sourcebase+'0')){
printf("Error!!! number cannot be less than zero.\n\n");
system("pause");
break;
}
}
if (i < length) continue;

printf("Enter a target base between 2 and 10:");
scanf("%d",&targetbase);
if((targetbase<2||targetbase>10)){
printf("Invalid!!!Your target base must be between 2 an 10\n\n");
system("pause");
continue;
}
break;//Added break to end the looping(figured that out by myself Yippee I'm learning!!!
}while(1);

//the program moves forward but the decimal i get is incorrect or it is correct....
for (int j=length-1; j>=0;--j){
decimal+=(number[j]-'0')*pow((float)sourcebase,power);
power++;
printf("Decimal=%d",decimal);
}//yeilds Decimal=3Decimal=11Decimal=27 so where do the 3 and 11 come from?

>> break;//Added break to end the looping(figured that out by myself Yippee I'm learning!!!
didn't we already have that ? :)

>> }//yeilds Decimal=3Decimal=11Decimal=27 so where do the 3 and 11 come from?
The 3 and 11 are just the progress of the calculation in the loop. Only the last one counts !

123 in base 4 = 27 in base 10

Now, just finish the part that converts the decimal to the targetbase ...

0

wkellyaAuthor Commented:

didn't we already have that ? :) Oh well, so much for progress...:(

so how about
lentgth=strlen(newnumber);
k=length-1;

0

wkellyaAuthor Commented:

printf("Your number is:%s\n\n",new_number);//Is this how you print the entire array?
return 0;

do I need another aray to store the remainder
values and then calcualte the length of the array? Is theire an easier way to add the numbers to newnumber?

1) you calculate the length, and then start from the back
2) you start from the front, but need to keep track of all progress

Whichever you like best.

In any case, you're gonna code it exactly the same way you do it in your head or on paper.

0

wkellyaAuthor Commented:

i still don't understand :(

remainder=decimal%targetbase;
decimal=decimal/targetbase;
new_number[k]=('0' + remainder);
--k
//This isn't working How to I initialize k so the remainder is added to the newnumber array

Take the base 10 number 35. Now, how would you find out its base 3 representation ? Write down all steps, and I mean ALL of them. Write down your complete thinking process. And post that here. To get a good overview, write it down in steps : step 1, step 2, ...

0

wkellyaAuthor Commented:

divide 35 by 3 store the remainder divide the quotient by three until we get zero read up the remainders for the numbers. How do you store each remainder in a separate array index?

printf("Your number is:%c\n\n",new_number[l]);
}
return 0;
}
It would have been nice If could have printed the reversed string in one line but this is good enough.
Thanks for all your help and patience:)

>> 1) Why am I repeatedly getting my error message even when my number isn't negative
Which sourcebase do you enter and which number ?

>> 2) I added a quit while statement and its given me an error on execution
First of all, I see a } that doesn't match.
What's "//conversion" supposed to do ?
What do you want to achieve by this quit loop ?

0

wkellyaAuthor Commented:

1)Say I enter 5 for the sourcebase and positive 345the error comes up but the progrma moves forward. I thought thr error was only supposed to report negative numbers why are numbers the are numbers >=sourcebase+'0' also invalid?

2)Quit offers the option to exit or start over so I wrapped it around the entire program

do{

do {
/* Get user information*/
system("cls");
printf("Enter a source base between 2 and 10:");
scanf("%d",&sourcebase);
if((sourcebase<2||sourcebase>10)){
printf("Invalid!!!Your source base must be between 2 an 10\n\n");

continue;
}
printf("Enter a positive number:");
scanf("%s",number,49);
length=strlen(number);

for(int i=0;i<length;i++){
if((number[i]<'0')||(number[i]>=sourcebase+'0')){
printf("Error!!! number cannot be less than zero.\n\n");

break;
}

if (i<length) continue;
}
printf("Enter a target base between 2 and 10:");
scanf("%d",&targetbase);
if((targetbase<2||targetbase>10)){
printf("Invalid!!!Your target base must be between 2 an 10\n\n");

continue;
}
break;
/* Validate User Data*/
}while(1);
/* Convert to Decimal*/
for (int j=length-1; j>=0;--j){
decimal+=(number[j]-'0')*pow((float)sourcebase,power);
power++;

>> 1)Say I enter 5 for the sourcebase and positive 345
345 is an invalid base 5 number. Base 5 numbers can only contain digits between 0 and 4 (0, 1, 2, 3, 4)

>> the error comes up
That's whay the error is shown

>> but the progrma moves forward.
The program moves forward because you put this line :

if (i<length) continue;

inside the for loop. It has to be put just AFTER the for loop.

>> I thought thr error was only supposed to report negative numbers why are numbers the are numbers >=sourcebase+'0' also invalid?
As I said above, 345 is an invalid base 5 number. Errors will be reported for EVERY invalid sourcebase number. So, if you put in any other character than the allowed digits, an error will be reported. And that includes negative numbers.

>> 2)Quit offers the option to exit or start over so I wrapped it around the entire program
OK, let's look at your code then :

1) before this line :

>> int string_length = strlen( new_number ) ;

put this line :

new_number[k] = '\0';

to terminate the string with a null - this is to make sure that strlen will work correctly !

2) This :

for( int l = string_length - 1; l >= 0; --l ){

printf("Your number is:%c\n\n",new_number[l]);

printf("Enter Q to quit, C to continue >");
scanf("%c", quit);

}

is not what you want to do. It's gonna give you this output :

Your number is : 1

Enter Q to quit, C to continue >
Your number is : 2

Enter Q to quit, C to continue >
Your number is : 3

Enter Q to quit, C to continue >

And you want it to show :

Your number is : 123

Enter Q to quit, C to continue >

So, replace it with this code :

printf("Your number is: ");
for( int l = string_length - 1; l >= 0; --l ){
printf("%c",new_number[l]);
}
printf("\n\n");
printf("Enter Q to quit, C to continue >");
scanf("%c", quit);

0

wkellyaAuthor Commented:

I'm still getting an unhandled exception error on execution saying i was trying to write to a corrupted part of memory

printf("Your number is: ");

for( int l = string_length - 1; l >= 0; --l ){
printf("%c",new_number[l]);
}
printf("\n\n");
printf("Enter Q to quit, C to continue >");
scanf("%c", quit);

char number[50]={ '\0' };
char new_number[50]={ '\0' };
int sourcebase=0;
int targetbase=0;
int length=0;
int decimal=0;
int power=0;
int remainder=0;
char quit={'0'};

do{

do {
/* Get user information*/
system("cls");
printf("Enter a source base between 2 and 10:");
scanf("%d",&sourcebase);
if((sourcebase<2||sourcebase>10)){
printf("Invalid!!!Your source base must be between 2 an 10\n\n");

continue;
}
printf("Enter a positive number whose digits are less than source base:");
scanf("%s",number,49);
length=strlen(number);
int i=0;
for( ;i<length;i++){
if((number[i]<'0')||(number[i]>=sourcebase+'0')){
printf("Error!!! number cannot be less than zero.\n\n");

break;
}
}
if (i<length) continue;

printf("Enter a target base between 2 and 10:");
scanf("%d",&targetbase);
if((targetbase<2||targetbase>10)){
printf("Invalid!!!Your target base must be between 2 an 10\n\n");

continue;
}
break;
/* Validate User Data*/
}while(1);
/* Convert to Decimal*/
for (int j=length-1; j>=0;--j){
decimal+=(number[j]-'0')*pow((float)sourcebase,power);
power++;

for( int l = string_length - 1; l >= 0; --l ){
printf("%c",new_number[l]);
}
printf("\n\n");
printf("Enter Q to quit, C to continue >");
scanf("%c", quit);

>> I'm still getting an unhandled exception error on execution saying i was trying to write to a corrupted part of memory
Where do you get the error ? With which input ? What's the exact error message (complete) ?

0

wkellyaAuthor Commented:

On program execution after
Enter Q to quit, C to continue > iis displayed
a window pops up saying the solution has encountered an error and needs to close
Then I see Unhandled exception:System.AccessVoilationException: Attempted to read write protected memory. This is often an indiction that other memory is corrupt.
at scanf(SByte*)
at main() in baseconvertor.cpp line 90

In this FREE six-day email course, you'll learn from Janis Griffin, Database Performance Evangelist. She'll teach 12 steps that you can use to optimize your queries as much as possible and see measurable results in your work. Get started today!

Why are you limiting num to 2 ... 10. If I understood your assignment correctly, you should limit sourcebase, and destbase.

I suggest you write two functions :

int from_base_x(char *num, int base);

char *to_base_x(int i, int base);

from_base_x will convert a string in base x to an integer and return it.

to_base_x will convert an integer to a string in base x and return it.

Then you can call these functions as follows :

int tmp = from_base_x(num_str, sourcebase);

char *result = to_base_x(tmp, destbase);

fprint("result : %s\n", result);

free(result);

num_str should be a string of course.

Can you give that a go, and show what code you can come up with for those functions ?