c - Conversion character, and fgets() function didn't work as expected -
i trying write code find size of data types , here code:
#include <stdio.h> #include <limits.h> #include <string.h> int main(int argc, const char * argv[]) { // insert code here... printf("choose 1 of following types relevant storage size\n(int, float, double, short, long, char: "); char mytype1[7] = ""; char mytype2[4] = "int"; char mytype3[7] = "double"; char mytype4[6] = "short"; char mytype5[5] = "long"; char mytype6[5] = "char"; char mytype7[6] = "float"; scanf("%s", mytype1); // fgets(mytype1, 7, stdin); if (strcmp(mytype1, mytype2) ==0){ printf("the 'int' variable size %lu\n", sizeof(int)); } else if (strcmp(mytype1, mytype3) ==0){ printf("the 'double' variable size %lu\n", sizeof(double)); } else if (strcmp(mytype1, mytype4) ==0){ printf("the 'short' variable size %lu\n", sizeof(short)); } else if (strcmp(mytype1, mytype5) ==0){ printf("the 'long' variable size %lu\n", sizeof(long)); } else if (strcmp(mytype1, mytype6) ==0){ printf("the 'char' variable size %lu\n", sizeof(char)); } else if (strcmp(mytype1, mytype7) ==0){ printf("the 'float' variable size %lu\n", sizeof(float)); } else { printf("incorrect choice\n"); } return 0; }
my questions are:
why xcode didn't accept conversion character except %lu, instance have tried '%d' 'int' statement getting warning argument has type 'unsigned long'?
scanf() function worked me, not fgets() function.
as understand size parameter in fgets() function maximum size can hold , not met (so if less size ok), why wasn't able use fgets() function instead scanf().
thanks.
for first of problem, sizeof
return value of type size_t
alias unsigned long
, hence why "%lu"
format works. however, should not use format, instead should using "%zu"
specified have size_t
argument (see e.g. printf
(and family) reference).
as second question, have remember fgets
can include newline (if fits) in string. have explicitly check , remove it:
if (fgets(mytype1, sizeof(mytype1), stdin) != null) { if (mytype1[strlen(mytype1) - 1] == '\n') // last character newline? mytype1[strlen(mytype1) - 1] = '\0'; // yes, change string terminator }
Comments
Post a Comment