$\require{cancel}$
Basic C++ I/O
- C++ I/O is part of the standard library.
- To use it you need to include
iostream
-
cin
is the standard input stream
-
cout
is the standard output stream
- Let's start with output.
- Examples:
-
cout << "Please enter your name =>";
-
cout << endl;
-
cout << greeting << endl;
- There are three basic components
- The output stream (
cout
)
- The stream insertion operator (
<<
)
- The end of line manipulator (
endl
)
- As well as the data to be inserted into the stream.
- The output stream
cout
- is normally associated with the terminal display connected to the program (the screen)
- This does not have to be the case, but it is the default behavior.
- Think of it as a place to put text/data/...
- The stream insertion operator (<<)
- Has data on the right hand side (lie)
- And a stream on the left hand side (truth)
- It converts the data on the right hand side to ascii and inserts it into the stream on the left hand side.
- It then returns the stream so the operation can be repeated.
- endl
- will send the newline character (\n) to the stream
- Will "flush the output buffer"
- Look at the examples above.
- Standard input
- This is more complex, we will revisit a number of times.
-
cin >> variable
- This attempts to read ascii text from the input stream and store it in the variable.
- It does the following:
- skip any leading white space.
- when non whitespace is encountered
- Attempt to convert this to the type of the variable character by character.
- If successful it stores the result in the variable.
- Stop when
- the conversion fails.
- a whitespace is encountered.
- This is easy with strings
- skip all whitespace
- store all non whitespace characters in the string
- stop when whitespace is encountered.