1) { errorNet(); } if (input[0] == '\n') { errorNet(); } if (...">

How can I trap the enter key ('\ n')?

    scanf("%s", input);

    if (strlen(input) > 1) {
        errorNet();
    }

    if (input[0] == '\n') {
        errorNet();
    }

    if (input[0] == '\0') {
        errorNet();
    }

      

When I press Enter, scanf moves to the next line and continues searching for input. How can I establish that if the input is hit, the errorNet function is called?

Ex. If input / empty string is entered, call the errorNet function.

+3


source to share


1 answer


If you are using fgets

, you specify the size of the line you are reading. fgets

will stop reading input when this size is reached or the user is pressed \n

. Note that this size counts \0

at the end of the line.

char input[10];
fgets(input, 10, stdin);
printf("%s\n", input);

      



To detect that the user just clicked \n

without writing anything, just check if the first character is \n

, e.g .:

if (input[0] == '\n') {
    printf("just '\\n'\n");
}

      

+1


source







All Articles