Hi there,
I am following a C programming self-study book and was introduced to char and ctype.h with the following example. Unfortunately, the book doesn't thoroughly explain some stuff and I hope you can enlighten me.
Code:
#include <stdio.h>
#include <ctype.h>
int main(void){
/*1*/ char value;
int number;
printf("\nChoose (o)ctal, (h)exadecimal oder (A)SCII > ");
/*2*/ value=getchar();
printf("\nGive decimal number : ");
scanf("%i",&number);
switch(toupper(value)){
case 'O':
/*3*/ printf("Decimal %i = Octal %o \n",number,number);
break;
case 'H':
printf("Decimal %i = Hexadecimal %x \n",number,number);
break;
case 'A':
/*4*/ if(number<=255)
printf("ASCII-Code %i corresponds %c \n",number,number);
else
printf("This number is too large!\n\a");
break;
}
return 0;
}
Ok.
1) The book explains char as a variable type that covers 1 byte (8bit), so 2^8=256 different signs. Does this mean that each sign is an int and char is just a substitute for 256 possible ints from which one can choose? Moreover, the first 128 signs are standardised in ASCII-code. When I run the program with octal, hexa, or ASCII, I don't quite understand what I should expect and if my C version (or whatever) is correct. When choosing ASCII (option A) and type decimal e.g. 11, I get a sign like this [?] instead of a biological male symbol - other decimals like 8 or 15 also give this question mark. The correct symbol given out according to my book starts not sooner than with the decimal input of 65, which gives the ASCII-sign A. Do I make any mistake somewhere or how can I make all decimals work?
2) Getchar() is a function, that's why the () are needed. The book says that opposite to scanf, getchar can only be used to read single signs. What does this mean exactly? And can't I write scanf("%f,%i",&abc,&xyz); for reading two variables at once? The way I interpret the use of getchar here is that we have three options and getchar should accept any of these three - 256 would be possible, but we only have three, and any other than "A", "O", or "H" doesn't do something with the program (no case arguments afterwards). Is this interpretation correct? How could this program be written if we wanted to only use ints?
3) This "number,number" at the end is not logic to me. The decimal I chose is the number and is inserted in %i. But %o, %x or %c refer to the value that I chose with (O)ctal, (H)exa, or (A)SCII. So for me, it should logically be "number,value". I suppose I am wrong. Why?
4) For the ASCII-option there is an if function given and an argument (number<=255). Why does only the ASCII-option have this argument?
Thank you very much for your helpful clarifications! They will help me going on with my book.