1

I want to take a line of string in C. How to do that? if I use format specifier %s in printf, it would only take characters upto first whitespace.How to get rid of it? is there any other way except using getline? Thanks in advance.

4
  • 1
    did you mean scanf there ? Commented Jan 8, 2013 at 12:58
  • 1
    @chris: That page also says, "Never use gets()." Commented Jan 8, 2013 at 12:59
  • @chris and suggests you use fgets instead Commented Jan 8, 2013 at 13:00
  • @Oren, Yeah, and I didn't see the note about the _s version being optional. Seemed like fgets with one less argument, but if it's optional, meh. en.cppreference.com/w/c/io/fgets Commented Jan 8, 2013 at 13:01

1 Answer 1

2

scanf is a poor choice for getting lines out of an input stream. While you can do it quite easily:

buf[SIZE];
scanf ("%[^\n]\n", buf);

You will be at the risk of being subject to a buffer overflow error/attack.

The better way is to read 'SIZE' characters at a time using fgets, and copying the data into a dynamically allocated buffer that you can resize upon filling it up:

buf[SIZE];
do {
  fgets (buf, SIZE, stdin);
  /* Handle copying to dynamic buffer and resize over here */
} while (/*check we haven't reached eol*/);
Sign up to request clarification or add additional context in comments.

1 Comment

"%[^\n]\n" gives the impression that after getting text before the EOL, the EOL (and only the EOL is consumed). Instead EOL and all the following whitespace is consumed. Alternative idea "%[^\n]%*c". But as you suggest fgets() is the way to go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.