Thread: Why does this line of code loop infinitely?

  1. #1
    Registered User
    Join Date
    Oct 2020

    Why does this line of code loop infinitely?

    Hi everyone,

    Why does this line of code produce an infinite loop upon receiving invalid input, and how do I fix it?
    for (int i = 0; !i; i = scanf("%lf", &myDouble)) puts("Please enter a double: ");
    I am just trying to prompt the user for input until myDouble is, in fact, a double (i.e. when the scanf() function returns non-zero). I get similar results using a do ... while loop:
    do {
      puts("Please enter a double: ");
    } while (!scanf("%lf", &myDouble));

  2. #2
    Registered User
    Join Date
    Dec 2017
    You need to clear the bad input or it will be read over and over again.
    #include <stdio.h>
    int main() {
        double d;
        while (puts("Enter a double: "), !scanf("%lf", &d))
            for (int c; (c = getchar()) != EOF && c != '\n'; ) ;
        return 0;
    Ordinary language is totally unsuited for expressing what physics really asserts.
    Only mathematics can say as little as the physicist means to say. - Bertrand Russell

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 11-09-2018, 09:42 AM
  2. Loop is running infinitely.please help...
    By V8cTor in forum C++ Programming
    Replies: 2
    Last Post: 08-07-2014, 01:38 AM
  3. whenever i delete a node and call display loop runs infinitely
    By Naveen Bansal in forum C Programming
    Replies: 1
    Last Post: 09-30-2012, 12:05 AM
  4. Infinitely looping inclusion!
    By kidburla in forum C++ Programming
    Replies: 3
    Last Post: 11-29-2005, 07:40 PM
  5. is there an infinitely large integer type?
    By MKashlev in forum C++ Programming
    Replies: 7
    Last Post: 08-10-2002, 02:31 PM

Tags for this Thread