Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

When is it preferable to use getchar() and when a string in c? As in K&R beggining, they only use getchat().?

2 Answers

Relevance
  • 3 years ago
    Favorite Answer

    Use getchar() to get characters one at a time from the console, and use either getc() or fgetc(). (getc and fgetc are the same, except that fgetc is guaranteed to be a function, while getc might be implemented as a #define macro.)

    Use fgets() to read whole lines (or all of a line that will fit into your char[] array.) Do this when you'll need to either want to use either array or pointer syntax to process the characters in a line--either because you need to scan twice or maybe just because it's easier to write. Also use whole line input when you want to pass the line (or part of it) as an argument to a function that expects a string.

    Do not use gets() ever. It does not detect input lines that are too long for the buffer, and there's no way to fix it. It was removed from the C Standard Library in the 1999 ISO standard. The 2nd and last edition of K&R was written before that, and gets() is mentioned. To his credit, Brian Kernighan avoids using it, preferring fgets() or his own getline() function, but does not say what was already known by the time the 1st edition was written: gets() was a mistake in the original library design.

    Oops: gets() was only *deprecated* in 1999, then removed in 2011. It never should have made it into the original 1989 ANSI standard.

  • ?
    Lv 7
    3 years ago

    getchar() is used when you want a single character.

    you can use fgets() to get a string -- several characters zero termntaed

    getchat() does not exist in the standard library.

Still have questions? Get your answers by asking now.