Ad space (banner)
๐ŸŽObjective-C Lessons
Lesson 58 / 68

Reading a value from standard input

This lesson covers reading standard input with fgets in Objective-C, with the aim of writing programs that handle input from a user.

The C-derived function fgets() reads one line of input from the keyboard. Use it when a command-line tool needs the user to type something.

The sample code receives a string from standard input with fgets(name, sizeof(name), stdin) and strips the newline by finding its position with strcspn(name, "\n"). Note that C-style input handling works unchanged in Objective-C.

A common early stumble is bridging between C-style input and the NSString world. Standard input arrives as a C character array, so handling it as an NSString means converting.

In professional work, using an input value without validating it leads to unexpected errors, so pairing it with a check is the safe approach.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Objective-C directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)