Thread: explain this loop statement?

  1. #1

    explain this loop statement?

    Hello people!
    I am learning C programming for sometime.Some days before i got this problem.Problem is that i cannot understand this While Loop!
    Statement is..
    ----while(scanf("%i",&j) != 1){
    while(( ch = getchar() != '\n')
    printf("Enter your integer:");
    Some other loops similar to Above are also used in that book.The problem is I do not know why he first tested the value of variable "j" against "1" in first scanf().As scanf takes the input from keyboard and then saves it in "j" but why it is tested against "1" .
    The author explains nothing ,he says that there is a problem in buffering characters in scanf() so to avoid this we use this loop?
    ------Also explain that why he put ""Do Nothing loop"" in the statement .I try to understand this one according to my information it is taking input by getchar() assigning this value to "ch" and testing it against "\n" which is for Enter key but why we put ; on next line....
    I would be thankful if you would explain this????

  2. #2
    Here's part of it. Scanf returns the number of items scanned. When scanf returns 0, it has failed. When scanf returns 1, it has scanned 1 item. In other words, he is saying keep going until you get something.
    \n is the newline character, and I think he wants to keep junking it until you get input. That's why he uses the infinite loop.
    I don't like the code.
    Some of the other guys will have better answers.

  3. #3
    Join Date
    Aug 2001
    Groningen (NL)
    The function scanf returns EOF if an input failure occurs, else it returns the number of input items assigned. So the author uses the comparison with 1 to check if:

    - input went correct (not equal to EOF)
    - one item is assigned (which is j)

    The function getchar is used to input a character. The character which you enter is stored in ch. If ch, which is the character, is not equal to '\n', the loop keeps going. When you enter '\n', then the loop ends.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Visual Studio Express / Windows SDK?
    By cyberfish in forum C++ Programming
    Replies: 23
    Last Post: 01-22-2009, 02:13 AM
  2. infinite while loop inside a switch statement.
    By tummala_005 in forum C Programming
    Replies: 6
    Last Post: 12-15-2008, 05:46 PM
  3. Replies: 26
    Last Post: 06-15-2005, 02:38 PM
  4. for loop or while loop
    By slamit93 in forum C++ Programming
    Replies: 3
    Last Post: 05-07-2002, 04:13 AM
  5. Uh-oh! I am having a major switch problem!
    By goodn in forum C Programming
    Replies: 4
    Last Post: 11-01-2001, 04:49 PM