Thread: something that isnt supposed to happen but does anyway

  1. #1
    Registered User
    Join Date
    Feb 2002
    Posts
    465

    something that isnt supposed to happen but does anyway

    i have never run into this problem before, but suddenly ive had two programs in a row that have started doing this, and i cant figure out why.

    a snippet of my code goes as follows:

    //...
    printf("Chose [blah blah] \n");
    scanf("%d\n", &choice);
    //[execute choice]

    and every time the program runs it makes you input twice... this is the output i get:

    Chose [blah blah]
    [user inputs number and hits enter]
    [number displays, but nothing else happens so user inputs number again]
    [choice executes]

    why is it making me put in the input twice? i have written two seperate programs lately that have this problem, and ive written numerous programs before in which i have never had a problem with it.

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    It does that because scanf is retarded. If possible avoid using it for many reasons. cin also has a similar problem in that when the user enters input and hits enter, the newline remains in the input stream. The next call to cin or scanf or any character input function will result in the newline being read. The problem can be solved by either using
    cin.ignore();
    or
    while ( getchar() != '\n' );

    Both of which will clear the input stream by reading and discarding everything up to and including a newline. How do you avoid the problem altogether? Use fgets and cin.getline() to read everything into a string and parse that string into the data you need

    -Prelude
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Feb 2002
    Posts
    465
    hmm......


    being here just makes me feel retarded.

  4. #4
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    You might try scanf() without the newline(\n).

    Instead of:
    scanf("%d\n", &choice);

    Try:
    scanf("%d", &choice);

  5. #5
    Registered User
    Join Date
    Feb 2002
    Posts
    465
    yeah, it works now.... thanks guys

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. magic could happen on recvfrom
    By -EquinoX- in forum C Programming
    Replies: 22
    Last Post: 03-27-2009, 06:06 PM
  2. Is This Supposed To Happen? [Dynamic Memory]
    By Dark Dude in forum C Programming
    Replies: 3
    Last Post: 03-21-2009, 05:41 PM
  3. I don't think this is supposed to happen.
    By Mako Eyes in forum C++ Programming
    Replies: 13
    Last Post: 11-03-2002, 07:29 PM
  4. Hey, what would happen if...
    By Imperito in forum A Brief History of Cprogramming.com
    Replies: 8
    Last Post: 04-05-2002, 08:54 AM
  5. What would happen?
    By DavidP in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 04-04-2002, 10:54 AM