previous | start | next

Using a Loop with String Sentinel

Suppose a program needs to read integer values from user input.

If -1 is not valid input for the program, it could be used as a sentinel indicating end of input.

A more general approach is to allow the user to enter a String such as "quit" or "exit".

How can we write a loop to repeatedly read integers from a user until the user enters "quit"?

Answer: Read the input as a string. If it is "quit", then stop reading.

If the input string is not "quit", convert it to an integer, process it, and repeat.



previous | start | next