Comp 110 Prompting

Prompting

The introcs library gives you 3 functions that allow users to provide input.

  • promptString
  • promptNumber
  • promptBoolean

To make use of a prompt function in your code, you must import it!

import { promptString, promptNumber, promptBoolean } from "introcs";

When a prompt function is called the program pauses and must await user input.

promptString:

User must enter a string value. In the following code snippet, the string variable myName is assigned the user-provided string input.

let greeting = (name: string): string => {
    return "Hello, " + name;
};
let myName = await promptString("What is your name?");
print(greeting(myName));

If the user inputs "Michael Scott", the resulting output will be: Hello, Michael Scott

promptNumber:

User must enter a numerical value. In the following code snippet, the number variable points is assigned the value of the user-provided numerical input.

let points = await promptNumber("How many points did UNC score?");
print("UNC scored " + points + " points in today's game!");

If the user inputs 102, the resulting output will be: UNC scored 102 points in today's game!

promptBoolean:

User must enter a boolean value. In the following code snippet, the boolean variable rain is assigned the value of the user-provided boolean input.

let rain = await promptBoolean("true or false: it is raining");
if (rain) {    
    print("Bring an umbrella!");
} else {    
    print("Enjoy the sun!");
}

If the user inputs true, the resulting output will be: Bring an umbrella! 

Note here that the variable rain is an expression that evaluates to a boolean value (true or false). Because rain is a boolean, we can use it inside of our if statement. By checking if (rain), we are really saying "if rain evaluates to true" -- when rain is true, we enter the then block of the if statement and continue on in the program.