Home

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):

int x;
cout << "Give me a number: ";
cin >> x;
cout << "You gave me the number " << x << endl;

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:

int x;
double y;
short z;
cout << "Enter three numeric values: ";
cin >> x >> y >> z;

This is equivalent to:

int x;
double y;
short z;
cout << "Enter three numeric values: ";
cin >> x;
cin >> y;
cin >> z;

More examples:

double a;
int x;
bool p;

cout << "Enter a decimal value: ";
cin >> a;
   
cout << "Enter an integer value: ";
cin >> x;
    
cout << "Enter a 0 for FALSE, anything else for TRUE: ";
cin >> p;

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:

double a;
int x;
bool p;
    
cout << "Enter a decimal, integer, and boolean value: ";
cin >> a >> x >> p;

We can get strings in the usual way:

string word;

cout << "Enter a word: ";
cin >> word;

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:

string s;

// get a whole line of text from the user
// and save into the variable s
getline(cin, s);

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:

cout.precision(3);
cout.setf(ios::fixed, ios::floatfield);

Here is a complete example:

#include <iostream>
using namespace std;
int main()
{
    double x;
    cout << "Enter value for x: ";
    cin >> x;
    
    cout.precision(3);
    cout.setf(ios::fixed, ios::floatfield);
    
    cout << "You entered " << x << endl;
    return 0;
}

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

#include <fstream>

Basic operations

ifstream f("myfile.txt"); // read as text
if(f.is_open())
{

}
f.close();
ifstream f("myfile.bin", ios::in | ios::binary); // read as binary data

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

string filename = "myfile.txt";
ifstream f(filename.c_str());

Reading

ASCII reading is just like cin:

int x;
f >> x;

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

char title[31]; // reserve space for a terminating \0
f.read(title, 30);
title[30] = 0; // set the terminating \0

Seeking

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

f.seekg(52); // go to byte 52

Boost Filesystem library

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

#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
using namespace boost::filesystem;

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

path p("somedir/somefile.txt");
bool ex = exists(p);
int size = file_size(p);
string pathstr = p.string();
string ext = p.extension();

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

path p("testdir");
for(directory_iterator it(p); it != directory_iterator(); ++it)
{
    path p2 = it->path();
    if(is_directory(p2))
    {

    }
    else if(is_regular_file(p2))
    {

    }
}

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

Example: Hexdump

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
using namespace boost::filesystem;
using namespace std;

int main()
{
    int offset = 1024;
    string filename = "test.bin";
    path p(filename);
    if(exists(p))
    {
        ifstream f(filename.c_str(), ios::binary);
        if(f.is_open())
        {
            f.seekg(offset);
            char bs[16];
            int filelength = file_size(p);
            for(int pos = offset; pos < filelength; pos += 16)
            {
                cout << hex << setfill('0') << setw(8) << pos << "  ";
                f.read(bs, 16);
                for(int i = 0; i < 16; i++)
                {
                    cout << hex << setfill('0') << setw(2)
                         << (int)(unsigned char)bs[i] << " ";
                    if(i == 7) { cout << " "; }
                }
                cout << " |";
                for(int i = 0; i < 16; i++)
                {
                    if(bs[i] >= 32 && bs[i] <= 126)
                    {
                        cout << bs[i];
                    }
                    else
                    {
                        cout << ".";
                    }
                }
                cout << "|" << endl;
            }
            f.close();
        }
        else
        {
            cout << "File cannot be opened." << endl;
        }
        
    }
    else
    {
        cout << "File doesn't exist." << endl;
    }

    return 0;
}
CSCI 221 material by Joshua Eckroth is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License. Source code for this website available at GitHub.