Q&A: Console input/output (cin/cout)

What library do you need to #include in order to display text to the screen and get input from the keyboard?

What library do you need to #include to use setw and setprecision?

What is the command to display output to the console?

cout << "Hello world!";

What is the command to display a new line to the console?

cout << endl << endl << "Hello!" << endl;

What is the output stream operator?

How do you display string literals and variable values in the same line?

cout << "Price: $" << price << ", Weight: " << weight << " lbs" << endl;

What are the commands to get input from the keyboard?

string name;
string category;
float price;
int amount;

cout << "Enter amount of item: ";
cin >> amount;

cout << "Enter price of item: $";
cin >> price;

cout << "Enter name of item: ";
cin.ignore(); // cin.ignore() required here.
getline( cin, name );

cout << "Enter category of item: ";
getline( cin, category );

What is the input srteam operator?

What are escape sequences? What does \t, \n, and \" do?

How do you format currency as USD?

cout << fixed << setprecision( 2 ); // Set up formatting

float price = 9.50;
cout << "$" << price << endl;

How does the setw command work?

Code:

const int COL1 = 35, COL2 = 10, COL3 = 10;

cout << left; // Set left alignment

// Display table header
cout
  << setw( COL1 ) << "NAME"
  << setw( COL2 ) << "PRICE"
  << setw( COL3 ) << "AMOUNT"
  << endl << string( 54, '-' ) << endl;

// Display data
cout
  << setw( COL1 ) << product1_name
  << setw( COL2 ) << product1_price
  << setw( COL3 ) << product1_amount
  << endl;

cout
  << setw( COL1 ) << product2_name
  << setw( COL2 ) << product2_price
  << setw( COL3 ) << product2_amount
  << endl;

Output:

NAME                               PRICE     AMOUNT
------------------------------------------------------
Penbrand Gel Pen                   1.89      20
Graphiteco Mechanical Pencil       1.75      15

Author: Rachel Wil Sha Singh

Created: 2023-10-27 Fri 15:26

Validate