c - Detecting the data type by reading a string -
so i've wondered, simplest way check user input (stdin). came conclusion, ideally scanf user input , print out results.
though i'm confused, how should this. here's thinking:
#include <stdio.h> int main(){ char input[30]; printf("please enter text\n"); scanf("%s", &input); ...
so here's part can't wrap head around of. i'd do, run through entire word (input), character character.
basically, if string consits of numbers (0-9), i'd input identified number. otherwise, detect string.
i've done fair bit of research (although keep in mind i'm absolute beginner), there way strcmp() function, i'd prefer avoiding other libraries, such string.h altogether , simple way, i've tried explain.
just it.
#include <stdio.h> int checkifnumber(const char *word) { /* check until string ends */ while (*word != '\0') { /* return 0 if character isn't number */ if (*word < '0' || '9' < *word) return 0; /* proceed next character */ word++; } /* no characters other numbers found */ return 1; } int main(void){ char input[30]; printf("please enter text\n"); scanf("%29s", input); if(checkifnumber(input)) { printf("%s number\n", input); } else { printf("%s string\n", input); } return 0; }
note character code numbers continuous in c, range-based method useful checking if character number (decimal digit). method may not work alphabets, on systems on non-ascii character code used.
n1256 5.2.1 character sets
in both source , execution basic character sets, value of each character after 0 in above list of decimal digits shall 1 greater value of previous.
Comments
Post a Comment