Comp 110 Prompting

Prompting

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

  • promptString
  • promptNumber
  • promptBoolean
  • csvToList

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

import { promptString, promptNumber, promptBoolean, csvToList } 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: string = await promptString("What is your name?");
print(greeting(myName));

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

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: number = await promptNumber("How many points did UNC score?");
print("UNC scored " + points + " in today's game!");

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

These two examples both made use of concatenation, of two strings and also of strings and numbers. For a review on this, please check out our page on concatenation.

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: boolean = await promptBoolean("Is it 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. Because rain is a boolean, we can use it inside of our if statement. For more review on this, check out our pages on expressions and operators and conditionals.