C code, scanf and getchar

I am just asking what getchar does in this code and how does it work? I don’t understand why getchar affects the code, it seems to me that it just gets the value, but nothing is done with the value.

int c=0;
while (c>=0)
{
  scanf("%d", &c);
  getchar();
}
+4
source share
4 answers

Some use getchar()cases can be used there:

1) If this is done to ignore spaces (usually used when scanning characters with %c), this is not required here, because %din any case it ignores spaces.

2) , , \n, scanf(), . , getchar() .

3) %d, scanf() . , int (, abcdddgdfg getchar()). , getchar() ( ), int ( %d).

; scanf(). scanf() . fgets() sscanf() strto*(), .

: , scanf? ?

+3

getchar : .

, . scanf , . getchar . , scanf , , , , STDIN.

, EOF, , , , scanf, (, , int). -

char *linep = 0;
size_t asize = 0;
char *endp;
long c;
while (getline(&linep, &asize, stdin) > 0) {
    errno = 0;
    c = strtol(linep, &endp, 10);
    if (linep == endp || *endp != '\0' || errno) {
        puts("?Redo from start");
        continue;
    }
    if (c == 0) break;
    do_something_with(c);
}
free(linep);
+1

, , .

scanf c.

( )

, , scanf , , , .

0
source

getchar(); - it's just reading and using the character after the number, whether it is a space, a comma, a new line or the beginning of another integer or something else.

IMO, this is not reliable code. Good code: 1) at least check the result scanf()and 2) check or limit the consumption of the next character in order to prevent the potential sign of the next number from being “eaten”. Remember that the code cannot control what the user enters, but must cope with what was entered.

    v space
"123 456"

    v comma
"123,456"

    v negative sign
"123-456"
0
source

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


All Articles