Need help managing user input

This is a discussion on Need help managing user input within the C Programming forums, part of the General Programming Boards category; Hey Everyone, I have an assignment to take an average of x numbers entered by the user. The problem I ...

  1. #1
    Registered User
    Join Date
    Nov 2006
    Posts
    3

    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...

    Code:
    #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]);
    
    return(0);
    
    }
    How do I break up the user entered string into separate int variables without knowing how many numbers the user is going to enter?

    Thanks

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,765
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Nov 2006
    Posts
    3
    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, 04:42 PM
  2. SSH Hacker Activity!! AAHHH!!
    By Kleid-0 in forum A Brief History of Cprogramming.com
    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, 07:37 AM

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