Thread: Read inputs separated by space

  1. #1
    Registered User
    Join Date
    Apr 2012
    Posts
    21

    Read inputs separated by space

    If I am reading input from a file such as

    Code:
    1 2 3 4 5
    How do I get my program to register each number as separate input?

    Thanks

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Look at scanf. When used with most* format specifiers, it will stop at or skip over white space (space, tab, newline). This works well for files like yours, with numbers. Use "%d" for integers, "%f" for floats and "%lf" for doubles. There are lots more options, but those should cover 90% of your cases. scanf is great for well formatted files, but can be a pain for user input or files where typos are common.

    * I say most. The behavior for reading characters (using "%c") is different, and the behavior for reading strings strings (using "%s") may be undesirable, i.e. you can't read multi-word strings.

  3. #3
    Registered User
    Join Date
    Mar 2011
    Posts
    546
    an alternative to scanf is to read a whole line with fgets and then separate the inputs with strtok.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Multiple inputs separated by EOF
    By juice in forum C Programming
    Replies: 35
    Last Post: 12-28-2011, 02:56 AM
  2. Obtain space separated values from text file
    By mammoth in forum C Programming
    Replies: 3
    Last Post: 04-20-2011, 04:49 AM
  3. Read UDP from kernel space
    By nabeshin in forum C Programming
    Replies: 0
    Last Post: 03-02-2010, 07:55 PM
  4. trouble with creating a loop to read certain number of inputs
    By import tuner650 in forum C++ Programming
    Replies: 2
    Last Post: 03-20-2008, 07:28 PM
  5. Read two words separated by a space with scanf at once
    By caduardo21 in forum C Programming
    Replies: 4
    Last Post: 06-23-2005, 04:17 PM