Thread: Need help managing user input

  1. #1
    Registered User
    Join Date
    Nov 2006

    Need help managing user input

    Hey Everyone,

    I have an assignment to take an average of x numbers entered by the user. The problem I have is that I don't know how to read an undetermined number of user inputted numbers into separate int variables. If I knew the amount of numbers the user was going to enter, then i'd use the following code to handle it...

    #include <stdio.h>
    char line[50];
    int number[3];
    int main()
           printf("Enter 3 numbers: ");
           fgets(line, sizeof (line), stdin);
           sscanf(line, "%d %d %d", &number[0], &number[1], &number[2]);
    How do I break up the user entered string into separate int variables without knowing how many numbers the user is going to enter?


  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    Look up the strtol() function.

    One of it's parameters allows it to return a pointer to where it got to in the line. Use this to advance your way along the line until you get to the end.

    You can achieve the same effect by using the %n conversion in sscanf.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Nov 2006
    Hey thanks a lot, Salem. I'll give that function a try.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. About aes
    By gumit in forum C Programming
    Replies: 13
    Last Post: 10-24-2006, 03:42 PM
  2. SSH Hacker Activity!! AAHHH!!
    By Kleid-0 in forum A Brief History of
    Replies: 15
    Last Post: 03-06-2005, 03:53 PM
  3. Nested Structures - User Input
    By shazg2000 in forum C Programming
    Replies: 2
    Last Post: 01-09-2005, 10:53 AM
  4. ~ User Input script help~
    By indy in forum C Programming
    Replies: 4
    Last Post: 12-02-2003, 06:01 AM
  5. Getting user input for filename loop
    By jpchand in forum C++ Programming
    Replies: 1
    Last Post: 09-16-2003, 06:37 AM