Reputation:
I am new to C and need some help here. I want to save all the zeros into a variable.
E.g:
int number1 = 0;
int number2 = 0;
int number3 = 0;
printf("Please enter the number in the following format( int,int,int)");
scanf("%d,%d,%d", &number1, &number2, &number3);
// Let's say user enters 1,000,000 (a million)
// I want to be able to print each of the numbers such as
// number1 = 1
// number2 = 000
// number3 = 000
At the moment when i do a printf statement for 1,000,000 i only get 1,0,0
My end goal here is to convert that decimal number to a binary number
Thanks for the help.
Upvotes: 2
Views: 209
Reputation: 16107
Try this:
char number1[80];
char number2[80];
char number3[80];
printf("Please enter the number in the following format(int,int,int)\n");
scanf(" %[0-9] , %[0-9] , %[0-9]", number1, number2, number3);
printf("%s, %s, %s", number1, number2, number3);
To convert a string to an int
, you can write atoi(numberx)
Upvotes: 2
Reputation: 16540
The posted code is reading three integers, separated by commas.
naturally, the results are 1 and 0 and 0
regarding this statement:
// Let's say user enters 1,000,000 (a million)
we can read it as a million, but the posted code (which reads three integers, separated by commas) will only see 1 and 0 and 0
To keep all the zeros, read the whole input as a char array. Then parse the actual number from the resulting char array by first squeezing out the commas, then converting to a single integer.
EDIT:
suggested algorithms to parse the actual value
char buffer[100];
int inputNum;
if( fgets(buffer, sizeof(buffer), stdin) )
{
for( char *source = buffer, char *destination = buffer;
*source;
source++ )
{
if( isdigit( *source ) )
{
*destination = *source;
destination++;
}
}
*destination = '\0';
inputNum = atoi( buffer );
}
there are simpler ways, like:
char buffer[100];
int inputNum = 0;
if( fgets(buffer, sizeof(buffer), stdin) )
{
for( int i=0; buffer[i]; i++)
{
if( isdigit(buffer[i])
{
inputNum *= 10;
inputNum += (buffer[i] - '0');
}
}
}
Upvotes: 2
Reputation: 45045
If you want to preserve leading zeroes, you should read the values as strings, rather than integers.
Upvotes: 3