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?
#include <iostream>
is required in order to use console input (cin
) and console output (cout
).
What library do you need to #include to use setw and setprecision?
#include <iomanip>
is required in order to usesetw
andsetprecision
commands.
What is the command to display output to the console?
cout
is used to display text to the console.
cout << "Hello world!";
What is the command to display a new line to the console?
endl
(end-line) is used to display new lines to the console.
cout << endl << endl << "Hello!" << endl;
What is the output stream operator?
- The
<<
sign for console output is known as the output stream operator.
How do you display string literals and variable values in the same line?
- Use the
<<
between each string literal and each variable name.
cout << "Price: $" << price << ", Weight: " << weight << " lbs" << endl;
What are the commands to get input from the keyboard?
- The
cin
(console-in) statement is used to get input from the keyboard. - We use
cin >> VARNAME;
for floats, ints, and single-word strings. - We use
getline( cin, VARNAME );
to get a line of text from the keyboard. - When going between
cin >> VARNAME;
andgetline( cin, VARNAME );
we must have acin.ignore();
in-between.
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?
- The
>>
sign for console output is known as the input stream operator.
What are escape sequences? What does \t, \n, and \" do?
- When written within double quotes,
"\t"
adds a tab-length of spaces to the console. - When written within double quotes,
"\n"
adds a new-line to the console.endl
is equivalent. - When written within double quotes,
"\""
displays a " to the console.
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