-4

I am working on pset4 of CS50 and really confused on where to use sprintf in recover.c problem of CS50.I want to know what and where to exactly use sprintf and printf.

Jonathan Leffler
  • 666,971
  • 126
  • 813
  • 1,185
  • 3
    read the man pages. – Sourav Ghosh Dec 03 '16 at 15:05
  • 1
    Well: the type of their first argument is different. – wildplasser Dec 03 '16 at 15:07
  • Google is your friend, you know. – Stef Dec 03 '16 at 15:15
  • "... where to exactly use ..": **only** in places where the function does what you need to do at that place. It makes no sense to use one if it doesn't do what you want it to do anyway, so in that case, use the other. (This advice can be extended to apply to all functions, with a final catch-all: if there is no such function, then write it.) – Jongware Dec 03 '16 at 15:18
  • 1
    @RadLexus: If there is no such function, then confirm that such a function's existence makes sense; if it does, then determine why nobody has written it yet; if there is no good reason (which is highly unlikely!) then write it. – Lightness Races in Orbit Dec 03 '16 at 15:19
  • @LRiO: one can even extend this philosophy to the entire width and depth of Software Development. "Is there software that does *x*? Is it useful to have software doing *x*?" If no & yes, ... Profit! – Jongware Dec 03 '16 at 15:22

1 Answers1

0

sprintf formats a string and writes it into the character array specified by the first argument (assuming sufficient space); printf formats a string and writes it to stdout.

Ex: you can do this with sprintf:

char buffer[100];
sprintf(buffer, "My name is %s and I am %d years old", "John Doe", 25);
// buffer now contains "My name is John Doe and I am 25 years old"

However, if you want to write a formatted string to the standard output stream, you need to use printf (or fprintf with stdout as the first argument):

printf("My name is %s and I am %d years old", "John Doe", 25);
// the text "My name is John Doe and I am 25 years old" gets printed to the stdout stream
Govind Parmar
  • 18,500
  • 6
  • 49
  • 78