# Input/output

## Stdin and stdout

You remember using cout to display a message. You can use cin to do the opposite: get input from the user. It works like this (notice the >> of cin, which are opposite those of cout):

You can use cin for integer types, floating point types, string types, and others. It’s easiest if you ask the user to enter one value at a time, pressing Enter between each value.

To acquire multiple values at once, just string them together with cin:

This is equivalent to:

More examples:

cin only collects input up to the first space or newline. It can be used to obtain multiple inputs. It knows when to delimit (i.e. start looking for the next input) when it reaches a space or newline (or tab).

Here’s the same example as above, but using just one cin:

We can get strings in the usual way:

However, using that technique, you cannot get strings that have spaces. To get strings that have spaces in them, we have to use this method:

That method gets a whole line of text, which could have spaces.

## Printing with precision

When printing “floating-point values” (such as floats, doubles, etc.) we often need to show a specific number of digits after the decimal point. This is known as the “precision” of the number. The actual precision of the value will not change; we will only change the printed precision. The following will show three digits after the decimal point:

Here is a complete example:

For example,

Enter value for x: 4.444444
You entered 4.444

Enter value for x: 0.0000001
You entered 0.000

Enter value for x: 123.45678
You entered 123.457


Notice how the last printout rounded up; the value of “x” inside the program has not changed, however.

## File Input

### Basic operations

If you have your filename in a string, you have to convert it to a “C-style” (old-style) string first:

ASCII reading is just like cin:

Binary reading reads into char arrays (byte arrays). The amount to read must always be specified:

### Seeking

You can jump to some byte position in the file with seekg:

## Boost Filesystem library

The Boost Filesystem library provides cross-platform access to files and directories (standard C++ does not).

Here are some of the things you can do with a path:

Here is how to read a directory (doing this recursively is left as an exercise for the reader):

When compiling, be sure to include the Boost Filesystem library with -lboost_filesystem -lboost_system:

g++ -Wall -ansi -o simple-ls -lboost_filesystem -lboost_system simple-ls.cpp