Thread: Scanf->Fgets

  1. #1
    Registered User 00Sven's Avatar
    Join Date
    Feb 2006
    Posts
    127

    Scanf->Fgets

    I was looking through my code for ScratchPad today and was trying to find ways to improve it. I decided to change all of the calls of scanf to fgets. Can someone post some code to show how to change the result of
    Code:
    fgets(string,sizeof(string),stdin);
    to exactly match the result of
    Code:
    scanf(" %s",string);
    I want to be able to switch it to fgets without needing to change any more code. I was hoping to make a function that I could run on a string after I use fgets() so that it will look just like scanf was used. Also on the topic of getting rid of scanf, what is the best way to replace this?
    Code:
    scanf(" %d",&i);
    Thanks in advance.
    ~Sven
    Windows XP Home Edition - Dev-C++ 4.9.9.2
    Quote Originally Posted by "The C Programming Language" by Brian W. Kernignhan and Dennis M. Ritchie
    int fflush(FILE *stream)
    On an output stream, fflush causes any buffered but unwritten data to be written; On an input stream, the effect is undefined. It returns EOF for a write error, and zero otherwise. fflush(NULL) flushes all output streams.
    board.theprogrammingsite.com

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    fgets just reads a block of input. It does no formatting. Try combining it with sscanf.


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

  3. #3
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Also on the topic of getting rid of scanf, what is the best way to replace this?
    Code:
    scanf(" %d",&i);
    There's nothing wrong with scanf(), especially if you check the return value.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. scanf() consideres useless
    By Snafuist in forum C Programming
    Replies: 15
    Last Post: 02-18-2009, 08:35 AM
  2. Help with a basic scanf procedure.
    By killpoppop in forum C Programming
    Replies: 9
    Last Post: 11-03-2008, 04:39 PM
  3. scanf issue
    By fkheng in forum C Programming
    Replies: 6
    Last Post: 06-20-2003, 07:28 AM
  4. Scanf and integer...
    By penny in forum C Programming
    Replies: 3
    Last Post: 04-24-2003, 06:36 AM
  5. scanf - data is "put back" - screws up next scanf
    By voltson in forum C Programming
    Replies: 10
    Last Post: 10-14-2002, 04:34 AM