If you run the following code you will get the ASCII characters, even though we use int i within %c inside the for loop.
#include <stdio.h>
int main()
{
int i;
for (i = 0; i <= 255; i++) /*ASCII values ranges from 0-255*/
{
printf("ASCII value of character %c = %d\n", i, i);
}
return 0;
}
Could you please advise how is this possible since there are characters inside ASCII?
Every variable in the computer is stored as binary and its value will depend on the type you define. For example, in memory store the value 1010. If you cast it as int, it will print -6, if you cast it as unsigned int, it will print 10. Same for int and char. It depends on you
printf() - Print formatted
we use format specifiers to specify the format of given variable,
%d format specifier to display the value of an integer variable.
%c is used to display character
as ASCII values ranges from 0-256 , %c will print the respective character symbol of number in Integer i
Related
wrote this code to "find if the given character is a digit or not"
#include<stdio.h>
int main()
{
char ch;
printf("enter a character");
scanf("%c", &ch);
printf("%c", ch>='0'&&ch<='9');
return 0;
}
this got compiled, but after taking the input it didn't give any output.
However, on changing the %c in the second last line to %d format specifier it indeed worked. I'm a bit confused as in why %d worked but %c didn't though the variable is of character datatype.
Characters in C are really just numbers in a token table. The %c is mainly there to do the translation between the alphanumeric token table that humans like to read/write and the raw binary that the C program uses internally.
The expression ch>='0'&&ch<='9' evaluates to 1 or 0 which is a raw binary integer of type int (it would be type bool in C++). If you attempt to print that one with %c, you'll get the symbol table character with index 0 or 1, which isn't even a printable character (0-31 aren't printable). So you print a non-printable character... either you'll see nothing or you'll see some strange symbols.
Instead you need to use %d for printing an integer, then printf will do the correct conversion to the printable symbols '1' and '0'
As a side-note, make it a habit to always end your (sequence of) printf statements with \n since that "flushes the output buffer" = actually prints to the screen, on many systems. See Why does printf not flush after the call unless a newline is in the format string? for details
In a memory, int take 4 bytes of memory you are trying to storing the int values in a character which will return the ascii value not a int value in %c if you are using a %d which will return the int value which are storing in a memory of 4 bytes memory.
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'm trying to print out the digits of an integer using the char format specifier.
This is what I currently have
//counter = arbitrary int
while (counter > 0) {
char c = (char)(counter % 10);
printf("%c", c);
counter/=10;
}
This just prints out blank but if I change the format specifier to int but leave the type cast, it'll print the correct value. Something like this
char c = (char)(counter % 10);
printf("%d", c);
Any ideas why this isn't printing when I use the char format specifier?
%c is for printing a character, not a number. If you want to print a number, you should use %d. The reason it works for char is because char is implicitly promoted to int when you pass it as an argument to a variadic function.
If c contained 'A', and you used %c to format it, you would get the letter ‘A’, but if you used %d, you would get its integer value, e.g. 65.
If you absolutely must use %c, you can add the value of '0' to the character before printing, e.g.L
printf("%c", c + '0');
%c can be used in this context as printf("%c",c+'0') where +'0' will turn it into the integer equivalent of c.
#include <stdio.h>
int main ( ) {
int n;
n = 0;
printf ("%c\n", n);
return 0;
}
so that's my code, but when i print it, it just prints a blank space. Shouldn't it print 0?
Change %c by %d:
printf ("%d\n", n);
n is integer type so try to print it as..
printf("%d\n",n);
and if u use %c then its printing first byte's related char in ASCII table .
If you need to display 0 without changing the printf statement, the way to do it is to do
n = '0';
or
n = 48;
Take a look at Ascii Table, to see the ascii value of 0.
Printf Writes the C string pointed by format to the standard output (stdout). If format includes format specifiers (subsequences beginning with %), the additional arguments following format are formatted and inserted in the resulting string replacing their respective specifiers.
Here you are Using wrong format specifier to print your value. %c used for printing variables of type char(character) . Use %d for int(integer).
Try this Link
In C is there a way to convert an ASCII value typed as an int into the the corresponding ASCII character as a char?
You can assign int to char directly.
int a = 65;
char c = a;
printf("%c", c);
In fact this will also work.
printf("%c", a); // assuming a is in valid range
If i is the int, then
char c = i;
makes it a char. You might want to add a check that the value is <128 if it comes from an untrusted source. This is best done with isascii from <ctype.h>, if available on your system (see #Steve Jessop's comment to this answer).
If the number is stored in a string (which it would be if typed by a user), you can use atoi() to convert it to an integer.
An integer can be assigned directly to a character. A character is different mostly just because how it is interpreted and used.
char c = atoi("61");
char A;
printf("ASCII value of %c = %d", c, c);
In this program, the user is asked to enter a character. The character is stored in variable c.
When %d format string is used, 65 (the ASCII value of A) is displayed.
When %c format string is used, A itself is displayed.
Output:
ASCII value of A = 65
#include <stdio.h>
#include <cs50.h>
int d;
int main(void){
string a = get_string("enter your word: ");
int i = 0;
while(a[i] != '\0'){
printf("%i ", a[i]);
i++;
}
printf("\n");
}