I'm here trying to convert 4-digit hexa into dec but didn't succeed.
Here is a my code.
unsigned int array[4];
printf("Type in 4-digit hexa: \n");
scanf("%x", &array);
while(getchar() != '\n');
printf("Your number in dec is %u \n", array);
I don't know what's wrong with it but it just wouldn't give out the correct dec output.
Like when I put in EEFF, it's supposed to give out 61183 but the program kept on printing out 65518.
Where's this number from? What's wrong with my code? I used unsigned int according to my consideration that FFFF is equals to 65385 and the range for unsigned int is 0 to 65535. There should be no problem with the range of data and I also used %u with it.
The only thing I can think of right now after I've done some searching is that this problem might has sth to do with the size of unsigned int to int or sth.
I read the explanation but didn't quite understand.
I know, this might be a duplication but I'm here asking for an easier explanation
of why this doesn't work. To be honest, I'm an absolutely newby for both this site and programming so please go easy on me with the coding. FYI, I don't really know anything outside of stdio.h .
You are passing a pointer, array, to printf(). There is no need for an array here, what you're trying to scan and print is a single number.
unsigned int number;
printf("Type in 4-digit hex:\n");
if (scanf("%x", &number) == 1)
printf("Your number in dec is %u \n", number);
Also note that it's considered a good idea to check if scanf() succeeds or not, by inspecting the return value.
You don't need an array for that:
unsigned int val;
printf("Type in 4-digit hexa: \n");
scanf("%x", &val);
printf("Your number in dec is %u \n", val);
a. print array[0], not array.
(optional) b. scan to array, not to &array.
c. what is the point of the getchar()?
No, you must input as string to a point of characters. After that, you convert to number.
Ex
char *str=char[10];
int i=0,num=0;
printf("Type in 4-digit hexa: ");
scanf("%s",str);
for(i=0;str[i]!='\0';i++)
if(str[i]>='0' && str[i]<='9') num=16*num+str[i]-'0';
else if(str[i]>='a' && str[i]<='f') num=16*num+str[i]-'a';
else if(str[i]>='A' && str[i]<='F') num=16*num+str[i]-'A';
printf("Dec is %d",num);
Related
I'm trying to write a short script to take in 6 inputs that will be in decimal, hex or octal and output their decimal versions. For example, if I input 1, 1 should be output. Input 010, should get 8, input 0x20, should get 32. Do I have to test each value to see if scanf reads it as its type or can I cast them after scanf reads them all as is? Also do I need functions to convert the octal and hex values to decimal or can I cast them? I'm very new to C and don't understand it well yet, but here's what I have so far (it outputs -200 as 32765 for whatever reason):
int num[6];
printf("Enter six integers:\n");
int i = 0;
int j;
while (i < 6){
if(scanf("0x%x", &j) == 1){
scanf("0x%x", &num[i]);
//hexToDec(num[i]);
} else if (scanf("0%o", &j) == 1){
scanf("0%o", &num[i]);
//octalToDec(num[i]);
} else {
scanf("%i", &num[i]);
}
i+=1;
}
for(int p = 0; p < 6; p+=1){
printf("%i\n", num[p]);
}
Answer for future reference: simply scanning in with "%i" does the conversions automatically. Revised code below:
int main(){
int num[6];
printf("Enter six integers:\n");
int i = 0;
while (i < 6){
scanf("%i", &num[i]);
i+=1;
}
for(int p = 0; p < 6; p+=1){
printf("%i\n", num[p]);
}
}
You cannot use scanf("0x%x", &j) to test the input and then use scanf("0x%x", &num[i]) to put the value in num[i]. scanf consumes the characters it accepts, so they are no longer in the input stream. When you do the second scanf, the characters are gone.
Instead, just attempt to scan the desired thing. If it works, you are done. If it does not work, go on to an else:
if (scanf("0x%x", &num[i]) == 1)
; // Worked, nothing to do.
else if (scanf("0%o", &num[i]) == 1)
;
else if (scanf("%i", &num[i]) == 1)
;
else
{
// Nothing worked, should put error-handling code here.
}
That is actually not great code for real applications, because scanf will consumes some of the input even if it ultimately fails. For example, with scanf("0x%x", &num[i]), if the input contains “0x” but then contains a non-hexadecimal character, scanf will consume the “0x” but leave the next character. However, it suffices for a learning exercise.
Once you have values in the num array, they are just int values. They are mathematical values, not numerals that are in octal, decimal, or hexadecimal. You can print them with %o for octal, or %d or %i for decimal. The original numeral is irrelevant. When printing, the mathematical value will be used to format a string in the requested base.
You should not use %x for printing an int, as %x is for unsigned int. However, you could convert an int to unsigned int and then print it with %x.
Note that you should not scan to int objects with %x. %x is for scanning to unsigned int objects. You can actually scan hexadecimal, octal, and decimal using:
if (scanf("%i", &num[i]) == 1)
;
else
…
The %i specification will recognize hexadecimal numerals beginning with “0x”, octal numerals beginning with “0”, and decimal numerals.
If you did not want to use %i for all three, because you want direct control for some reason, you will need to write more code. Standard C does not provide a direct way to scan only a hexadecimal numeral to an int. You would need to get the characters from the input and calculate the value from them or scan to an unsigned int and then convert the result to an int.
You can use function strtol with a base of 0 to do auto-detection of the integral value's base according to the input strings format (cf, for example, strtol documentation at cppreference.com):
long strtol( const char *str, char **str_end, int base )
Interprets an integer value in a byte string pointed to by str. ...
The valid integer value consists of the following parts:
(optional) plus or minus sign
(optional) prefix (0) indicating octal base (applies only when the base is 8 or 0)
(optional) prefix (0x or 0X) indicating hexadecimal base (applies only when the base is 16 or 0)
If the value of base is 0, the numeric base is auto-detected.
So a call like long val = strtol("0x10",NULL,0); will yield a decimal value of 16.
Note that you can also use scanf in conjunction with format specifier %i, since this is defined to behave just as a call to strtol:
int scanf( const char *format, ... )
%i matches an integer. The format of the number is the same as expected by strtol() with the value 0 for the base argument (base is
determined by the first characters parsed)
The quick answer is use only
if(scanf("%i", &j) == 1){
...
}
what I have so far (it outputs -200 as 32765 for whatever reason):
Yet error handing of scanf() is troublesome. Far better to read the line of user input with fgets() and then parse the line - perhaps with strtol().
I am trying to ask the user for an input, have that input be set as an unsigned char, and then print it out. For example, the input will ask me "Input x:" and I put in 0xABCD as the input. I need it to print out "0xABCD" as well.
Here's what I have so far:
unsigned char x;
printf("Input x:");
scanf("%s, &x);
printf("%u", x);
It gives me 0 instead of 0xABCD.
What am I doing wrong?
You need to use "%hhu" as the format specifier to read an unsigned char. See the table at http://en.cppreference.com/w/c/io/fscanf.
unsigned char x;
printf("Input x:");
scanf("%hhu", &x);
Note that if you use this format specifier, the input has to be a number. It cannot be a character. 65 will be a valid input but A won't.
Coming to your problem of wanting to use 0xABCD as input, that value is too large to fit into an unsigned char. You can use:
unsigned x;
printf("Input x:");
scanf("%x", &x);
To print that number as 0xABCD, you can use:
printf("0x%X\n", x);
If you don't mind the number being printed as 0xabcd, you can use:
printf("%#x\n", x);
A string is an array of characters terminated by '\0'. You're reading a string into a single character, which is undefined behavior.
Your code should really look something like this:
unsigned char x[64];
printf("Input x:");
scanf("%63s, x); /* use the size of buffer to prevent buffer overflows */
printf("%s", x);
In your code
scanf("%s, &x);
invokes undefined behavior. xis of type char and you cannot use %s to scan the value.
What you need is to define a char array at least to be able to hold your expected input.
If you like to have a second approach, you can do something like
scan the input as (unsigned) integer using %x
print the same using %#X format specifier.
See it live
In any ways "0xABCD" can't be treated as a 'char'. A char can store a 8 bit value, so from 0 to 255 (if unsigned), and the given number 0xABCD is equal to 43981.
You can read it as a string or read it as a hexadecimal value (which must be an unsigned). For this case an example:
unsigned int x;
printf("Number: ");
scanf("%x", &x);
printf("%d / %X\n", x, x);
will give:
Number: 0xABCD
43981 / ABCD
If treated as a string you will have to treat it an other way (sscanf…).
there is no char equivalent, use int instead.
int main(){
unsigned int x;
printf("Input x:");
scanf("%x", &x);
printf("\n%d (%#x)\n", x);
}
I would to do something like this:
int index=1;
for(index=1; index<10; index++)
printf("Welcome player"+index+". How are you today?");
I'm new in C programming and not sure how to concatenate an integer.
printf() has special format specifiers that enables you to inject variables into the resulting string. In your case you would want to do it like this:
printf("Welcome player %d. How are you today?", index);
See more info here.
what I think you are trying to do is this
char index[20];
printf("Enter Name: ");
scanf("%s", index);
printf("Welcome player %s How are you today?", index);
The reason we do the scanf is because we want user input, whatever the user will put in the scan f will come out as the output for your printf.
We use %s because index is a string, for things such as ints, floats, and chars you use %d, %f, or %c or else it wouldn't compile if you were trying to use %d if it was actually a string
at the end of the second printf we used the name of the integer we wanted to use, show the value within the string would print.
The array with the char index[20]; is to assume that the string will not be longer than twenty bits, if you wanted more than you can write however long you wish it to be, if you want it less you can write it to be small as 0 if you wished. (This would give it eight character input, because a byte can store 8 bits, so 8 characters).
I was teaching the C programming language to a friend and we came up with something I could not explain. This is the code we wrote:
#include <stdio.h>
int main(void)
{
char num1;
char num2;
printf("%s", "Enter the first number: ");
scanf("%d", &num1);
printf("%s%d\n", "The number entered is:", num1);
printf("%s", "Enter the second number: ");
scanf("%d", &num2);
printf("%s%d\n", "The number entered is:", num2);
printf("%s%d\n", "The first number entered was:", num1); /* This was done for testing */
printf("%s%d\n", "The sum is:", num1+num2);
return 0;
}
The weird thing is that we tried to do 5 + 6 and we expected to get 11 but instead got 6, I added a line to see what's going on with the first number and it becomes 0 after the second number is read.
I am aware that the variables should be an int (in fact the original code was like that and worked) but my understanding is that a char is a small integer so I thought it would be 'safe' to use if we were adding small numbers.
The code was tested and compiled on a Linux machine with cc and on a Windows machine with cl. The output was the same. On the Windows machine the program throw an error after the addition.
I would like an explanation on why this code is not working as I expected. Thanks beforehand.
You cannot pass a pointer to a different datatype to scanf. scanf will write to memory assuming you gave it a pointer to what it expected (e.g. int for %d), and will exhibit wonderful undefined behaviour if you give it a pointer to a different datatype.
Here, what is most likely happening is that scanf is overwriting e.g. 4 bytes on your stack when your chars only take up 1 byte, so scanf will just be happily writing right over some other variable on your stack.
a char is a small integer so I thought it would be 'safe' to use it if we were adding small numbers.
That is correct, char is a small integral type , and it's OK to use it in integer arithmetic(although char may be signed or unsigned which may causes the result unexpected).
But the problem is, a pointer to char can NOT be used in a place where a pointer to int is expected. And this is the case for scanf("%d", &num1);, the second parameter is expected to a of type int *.
I'm trying to write a short program were:
#include <stdio.h>
void main()
{
char=a,b,c;
printf("please place 3 numbers:\n");
scanf("%c%c%c", &a,&b,&c);
}
The exercise I'm trying to solve is how to change the char to int so if I write in a the number 3, I will get the number 3 Printed.
at this point I'm only getting the value.
I would appreciate any help.
The answer depends somewhat on what you can assume about the character set. If it's something like ASCII (or really, any character set that includes the digits in sequential order), you just need to offset the character value by the value of the character 0:
int aValue = a - '0';
I'm sure that C# provides better ways to do what you're trying to do, though. For example, see this question for some examples of converting strings to integer values.
First of all your syntax need some checking
You should know that you declare a variable this way (a char in this example):
char a;
If you want to declare multiple variables of the same type in a row you do :
char a, b, c;
If you want to assign a value to a declared variable :
a = '3';
Now to print a char using printf (man printf is a must read, more infos are in coreutils) :
printf("%c", a);
If you want to get the char from the command line, I recommand you to use getchar() (man getchar) instead of scanf because if suits better what you are trying to achieve and doesn't require you to use a syntax in scanf that I am sure you don't fully understand yet.
Your question is incredibly light on details, so here are several options:
#include <stdio.h>
int main()
{
char a,b,c;
printf("please place 3 numbers:\n");
scanf("%c%c%c", &a,&b,&c);
printf("Printing ints (auto-promotion): %d %d %d\n", a, b, c);
printf("Printing ints (explicit-promotion): %d %d %d\n", (int)a, (int)b, (int)c);
printf("Printing digits: %d %d %d\n", a-0x30, b-0x30, c-0x30);
return 0;
}
If the input is 123,
I expect the output to be:
Printing ints (auto-promotion): 49 50 51
Printing ints (explicit-promotion): 49 50 51
Printing digits: 1 2 3
Some things I fixed along the way.
main should return an int, not be void.
char=a,b,c; is a syntax error. You meant char a,b,c;
added a return 0; at the end of main.
You question is not quite understandable. Still I'll try to help. I think that what you want is to store an integer value in the char variable. You can do so by using the following code:
#include<stdio.h>
void main()
{
char a,b,c;
printf("Enter three numbers:\n");
scanf(" %c %c %c",&a,&b,&c); //notice the spaces between %c
}
Or if you want to enter a character and print its ASCII value, you can use the following code:
#include<stdio.h>
#include<conio.h>
void main()
{
char a,b,c;
printf("Enter three characters:\n");
scanf(" %c %c %c",&a,&b,&c);
printf("Entered values: %d %d %d",a,b,c);
getch();
}