C program won't allow input

This is a discussion on C program won't allow input within the C Programming forums, part of the General Programming Boards category; When i run this code, it does not give me an option to enter in my weight. Instead it goes ...

  1. #1
    Registered User caroundw5h's Avatar
    Join Date
    Oct 2003
    Posts
    751

    C program won't allow input

    When i run this code, it does not give me an option to enter in my weight. Instead it goes straight to printing the info i entered what did i do wrong?
    Code:
    #include <stdio.h>
    
    int main(){
    
    int age;
    float weight;
    char first[15], last[15]; /* 2 char arrays */
    
    
    printf("\nWhat is your first name?");
    scanf(" %s", first); /* no ampersand on char arrays */
    
    printf("what is your last name? ");
    scanf(" %s", last);
    
    printf("how old are you?");
    scanf(" %d", &age);
    printf("how much do you weigh? ");
    scanf(" %f", &weight); /*ampersand required*/
    
    printf("\n");
    printf("\nHere is the info you entered;\n");
    printf("name: %s %s\n", first, last);
    printf("weight: %d", age);
    
    system("pause");
    return 0;
    }

  2. #2
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    When you scanf() in a number, the newline character is left in the input buffer, meaning its the first thing to get read in next time.

    Two fixes:

    drop scanf()
    http://faq.cprogramming.com/cgi-bin/...&id=1043284385
    http://faq.cprogramming.com/cgi-bin/...&id=1043284385

    Flush the input buffer after you scanf() in a number:
    http://faq.cprogramming.com/cgi-bin/...&id=1043284392
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Client-server system with input from separate program
    By robot-ic in forum Networking/Device Communication
    Replies: 3
    Last Post: 01-16-2009, 02:30 PM
  2. Utter newb?: Program crashes after input
    By deductible in forum C++ Programming
    Replies: 5
    Last Post: 12-13-2008, 09:27 PM
  3. getting input from another program
    By adr in forum C++ Programming
    Replies: 6
    Last Post: 03-04-2006, 02:29 AM
  4. large program code ,please help
    By Ash1981 in forum C Programming
    Replies: 14
    Last Post: 01-30-2006, 05:16 AM
  5. Input via the serial port for a C program
    By Anthony in forum C++ Programming
    Replies: 2
    Last Post: 07-11-2005, 02:19 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21