Hello guys I am reading some book but there and went to input validation but there is something logical i dont get in it you know when press enter with getchar() sometimes it transmits newline to the program but book has solution but i don't know why it works i m confused about it

while (getchar() != 'y')   /* get response, compare to y */

{

    printf("Well, then, is it %d?\n", ++guess);

    while (getchar() != '\n')

        continue;          /* skip rest of input line    */

}

but this will discard rest of the line but the \n it wont discard it since the loop will quit when it reads \n ? shouldnt it be while(getchar()=='\n')
continue;
now it will discard it ?
wouldnt it be better to do this

while( we getting char not = eof) {
 if(char == '\n') 
          continue;//wouldnt it be better to use this ?
}

i know first one will discard every character but why does it discard the \n also ?

'Discard' in this case means that the character is extracted from the input stream so that the next read will return the character after it or EOF. getchar() always extracts a character if it can, so if '\n' is next in line, getchar() will remove it from the stream and return it to the program.

The ignore pattern while(getchar() != '\n') continue; discards all characters up to and including the first '\n' because before the loop can test the result against '\n', getchar() first has to extract it from the stream. If you do not want to ignore the '\n', it has to be pushed back onto the stream:

int c;

while ((c = getchar()) != '\n' && c != EOF)
{
    continue;
}

if (c == '\n')
{
    // push the line break back onto the stream
    if (ungetc(c) == EOF)
    {
        // could not push the character back
    }
}

oh so when loop see \n getchar() reads it and discards then quit the loop ? what i mean by quit is it will start another looping from beging so it discards the newline encountered by scanf right ?

oh so when loop see \n getchar() reads it and discards then quit the loop ?

The loop does not see '\n' until getchar() reads it, and by the time getchar() reads '\n', it has been extracted from the stream. So when the loop ends by comparing with '\n', the '\n' will not be read by the next input call.

thanks guys

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.