-2

There are several ways how to retrieve string input, e.g getline() , or fgets() but all of them require size of the string as an argument. But what if i want to retrieve string of unknown size? How is it possible using getline() or fgets() in C?

alk
  • 69,737
  • 10
  • 105
  • 255
Abdir
  • 87
  • 1
  • 1
  • 6

1 Answers1

2

The answer is no. You can't read a string of indeterminate length. You can, however, read one character at a time until you reach the size of the storage space you have allocated in your program. Use fgetc in a loop.

int fgetc(FILE *stream)

Open the stream , read one character at a time, and stop reading when you see your sentinel character, which is probably a newline.

nicomp
  • 4,344
  • 4
  • 27
  • 60
  • 1
    You can read a string of indeterminate length. There’s just no builtin to do it. – Ry- Dec 06 '15 at 14:00
  • Well, you can do anything at all, there's just no builtin to do it. – nicomp Dec 06 '15 at 14:06
  • (The reason I bring it up is that in “You can't read a string of indeterminate length. You can, however, read one character at a time until you reach the size of the storage space you have allocated in your program.”, the “other” option isn’t built-in either.) – Ry- Dec 07 '15 at 01:38
  • My answer describes exactly what you are saying, but technically it's not reading a string, it's reading a series of char items and saving them contiguously. – nicomp Dec 07 '15 at 01:43