C Language String Reading Function Overview

When the C Lords banished the gets() function into obscurity, cohorts of confused coders descended upon the fgets() function as a viable alternative. Alas, fgets() isn’t without its faults.

While fgets() is basically the gets() function with an input cap, it has one major difference: The fgets() function stores the Enter key character (newline or \n) at the end of the string. That makes it different from the gets() function, but it also requires overhead when you want to to deal with that extra character.

I suggest a fix to the fgets() function in this Lesson from June, 2013.

The other string input function despondent programmers turned to was scanf(), which isn’t really a string input function at all.

While scanf() is great for reading in discrete values, such as integers and floats, and it’s handy when you learn to program, the function doesn’t interface well with humans. It’s much better to receive human input in the form of a string, then deal with that input inside the code. (I’ll provide a specific rant about how dealing with human input in a future Lesson.)

The key thing to remember about scanf() and strings is that it stops reading characters at the first sign of whitespace.

Whitespace characters include the space, tab, and Enter.

That limitation means that scanf() can read words just fine, but not strings. Not unless you go all Roman and write everything without any spaces.

GALLIAESTOMNISDIVISAINPARTESTRES

I’m sure Caesar wouldn’t notice anything wrong with scanf() and strings.

Anyway, I wax poetic on scanf() in this Lesson from April 2014.

You can also craft your own input function, which I strongly recommend. I’ll demonstrate such a function in the next Lesson.

Also, the C library sports a solid input function getline(), which I’ll cover in a future Lesson.