Originally Posted by
BharatNT2IE
Hello, i am trying to make a comeback into C, i have the following doubts.
- When the compiler compiles the program, will i be able to see the debug messages, that the compiler is using when it compiles a line.
The compiler outputs error-messages if needed, and stops without producing the executable. It can also output warnings & notifications, but usually you have to enable them first.
If you are using any recent flavor of gcc, try adding -Wall -Wextra in the command-line options.
- char card_name[3] is a array, what is the significance of 3, is it the maximum characters in the array.
Yes. But since you are dealing with character arrays for treating them as c-strings via the standard library, the last character must be '\0'. That's why you need to define an extra space for it (in your case 3 instead of 2).
- What is the significance of %2s ?
It instructs scanf() to read only the first 2 characters.
- So i think you get the jist of the program. What if if i wanted to read the number 10. How can i generalize the program for all the 13 cards.
Generalizing would involve a more structural approach, assuming you want to avoid a long switch-statement or multiple if-else statements.
Here's a simplified way of doing it, by checking your input against the contents of two pre-defined arrays: one holding card labels, and one mapping corresponding card values.
Re-designing it using structs would be more scalable though...
Code:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define NFACES 13
char faceLabels[NFACES][3] = {
"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"
};
int faceValues[NFACES] = {
0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 11
};
/* ----------------------------------------
* Convert all characters of a cstring to upper-case
*/
void s_toupper( char *s )
{
if ( s )
{
while ( *s ) {
*s = toupper(*s);
s++;
}
}
}
/* ----------------------------------------
* Look for cstring label into the array of cstrings faceLabels.
* Return the index of label inside faceLabels on success, -1 otherwise.
*/
int faceLabel_lookup( const char label[3], char faceLabels[NFACES][3] )
{
int i;
/* sanity checks */
if ( !label || !faceLabels )
return -1;
for (i=0; i < NFACES; i++)
if ( 0 == strcmp(label, faceLabels[i]) )
return i;
return -1;
}
/* ---------------------------------------- */
int main( void )
{
char label[3] = {'\0'};
int faceIndex = -1;
puts("Enter label of the card: ");
scanf("%2s", label);
s_toupper(label);
faceIndex = faceLabel_lookup(label, faceLabels);
if ( -1 == faceIndex ) {
puts( "*** there's no such card" );
return 1;
}
printf( "The card value is: %d\n", faceValues[faceIndex] );
return 0;
}