Introduction to cout / cin
Purpose cout is used to print to the screen in a C++ Console Application. cin is used to read user input from the keyboard in a C++ Console Application.
#includes cout and cin are defined by the C++ standard library iostream. To use these utilites: #include <iostream> Additional utilities for formatting cout are in: #include <iomanip>
Basic Idea cout is a stream from the application (executing in memory) to the screen. Characters are inserted into the stream and “fall out” on the screen. I/O manipulations may be used to format the characters before they are written.
Basic Idea cout is a stream from the application (executing in memory) to the screen. Characters are inserted into the stream and “fall out” on the screen. I/O manipulations may be used to format the characters before they are written.
Basic Idea
Basic Idea
cout syntax cout << expression; where expression is a literal, variable or more complex expression that evaluates to one value.
cout syntax cout << expr1 << expr2 << ... << exprn; is equivalent to: cout << expr1; cout << expr2; ... cout << exprn;
cout style Can vary greatly depending on the situation. Make it clear to another programmer and easy to maintain.
cout style Good style: cout << ”+-------+\n”; cout << ”| Hello |\n”;
cout style Good style: cout << ”+-------+\n” << ”| Hello |\n” << ”+-------+\n”;
cout style Poor style: cout << ”+-------+\n| Hello |\n+-------+\n”;
iomanip Floating Point Numbers: // print floats/doubles in decimal format with // 2 digits past the decimal point. // Prints nothing. In effect until changed. cout << fixed << setprecision(2);
iomanip Field Widths: cout << setw(10) << ”Hello”; // set total field with of a value cout << setw(10) << ”Hello”; Prints 5 spaces then 5 characters: Hello
iomanip Field Widths: Prints 5 spaces then 5 characters then There // effect is only for 1 value cout << setw(10) << ”Hello” << ”There”; Prints 5 spaces then 5 characters then There HelloThere
Basic Idea cin is a stream from the keyboard to the console application (executing in memory) Characters are inserted into the stream by the user and are extracted by cin.
Basic Idea
cin Syntax: (simple) Semantics: in general cin >> variable; Read as: variable = whatever is entered by the user;
cin Semantics: in general - halts execution of the program - the user enters data and presses ENTER - the data is converted to the data type of the variable. - the data entered is stored in the variable - execution continues
cin Semantics: specifically Exactly how cin behaves depends on the: - data type of the variable - what is currently in "the stream", if anything. - data type of the data entered by the user
More Details Coming Soon! cin More Details Coming Soon! For now, assume that for each cin: - the user enters the correct data type - the user enters NO SPACES/TABS/etc - the user presses ENTER when done
cin examples
cin examples
cin examples