Thread: Best way to scan in a string

  1. #1
    Registered User
    Join Date
    Oct 2011
    Posts
    24

    Best way to scan in a string

    What is the best way to scan in a string that HAS white spaces if I want the scan to stop once it finds a '\n' character. I need to do this both from regular user input, stdin, and from a file. Should I use scanf, fscanf, or fgets? If so, what is the syntax to make the string stop getting data after it finds a newline character?

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Why don't you look up each function and read the documentation on them?
    scanf
    fgets


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Oct 2011
    Posts
    24
    Ive looked them up multiple times and everytime I try one, something ends up being wrong with the way I try to do it, so I come on here as ask what people think and they all give me different answers.. Some say use fgets, others say fgets is terrible or something...I'm just looking for a solid answer from someone who is experienced

  4. #4
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    It's gets that's "terrible". fgets is good because it takes a buffer size parameter. The only thing to note about it is that it leaves the newline in the string.
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  5. #5
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    If only there was some sort of FAQ on this topic. FAQ > Get a line of text from the user/keyboard (C) - Cprogramming.com


    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How do I scan patterns?
    By unknownC in forum C Programming
    Replies: 5
    Last Post: 10-16-2011, 02:22 AM
  2. Scan a string, present character
    By emdleb in forum C Programming
    Replies: 6
    Last Post: 02-11-2011, 10:21 AM
  3. scandisk? scan this!
    By Waldo2k2 in forum Tech Board
    Replies: 9
    Last Post: 12-22-2002, 12:21 PM
  4. scan a string
    By Max in forum C Programming
    Replies: 4
    Last Post: 12-02-2002, 04:26 PM
  5. while (scan != 'y' or 'n) or if(scan != 'y' or 'n)
    By Blizzarddog in forum C++ Programming
    Replies: 6
    Last Post: 10-23-2002, 01:16 PM