Data type detection by reading a string

So, I wondered what would be the easiest way to check user input (stdin). I came to the conclusion, ideally this would scan user input and print the results.

Although now I'm a little confused about how to do this. Here is what I thought:

#include <stdio.h>
int main(){

char input[30];    

 printf("Please enter text\n");
 scanf("%s", &input);

 ...

So, here is the part that I can’t wrap my head on. So, what I would like to do, runs through the whole word (input), character by character.

Basically, if a string contains only numbers (0-9), I would like the input to be identified as a number. Otherwise, define it as a string.

( , ), strcmp(), , string.h , .

+4
1

.

#include <stdio.h>

int checkIfNumber(const char *word) {
    /* check until the string ends */
    while (*word != '\0') {
        /* return 0 if the character isn't a number */
        if (*word < '0' || '9' < *word) return 0;
        /* proceed to the next character */
        word++;
    }
    /* no characters other than numbers found */
    return 1;
}

int main(void){

    char input[30];

    printf("Please enter text\n");
    scanf("%29s", input);

    if(checkIfNumber(input)) {
        printf("%s is number\n", input);
    } else {
        printf("%s is string\n", input);
    }

    return 0;
}

, C, , ( ). , , ASCII.

N1256 5.2.1

0 , .

+3

Source: https://habr.com/ru/post/1614044/


All Articles