Tag Archives: scanf

How to read keyboard input in C

We can use the scanf() function to get user input in C. Here’s a quick implementation of scanf():

scanf() will wait for the user to press Enter before giving its returned value back to our app. We must define a variable to hold its output. We can even define multiple variables, each of which will be populated with whatever is being typed in until Enter is pressed. Consider this:

Here we wait for three string items to be added (numbers entered will be interpreted as strings). To grab a numeric value from the keyboard, we cam use %d like so (d as in decimal, variable defined as int):

Note the ampersand in front of our variable, without which scanf would populate a pointer. We can also mix and match keyboard input like this:

Demo Project

You’ll find a quick demo project on GitHub, which also serves as a template on how to setup Xcode to open Terminal and allow for keyboard input when the project is run.