# C++ Notes: Reading Number or String

## Problem: The next input token could be either a number or a string

When using `cin` in the simplest way, you have to either specify a numeric or string variable to read into. But there are problems where the input may be either a number or a non-numeric token (eg, string), and you must read it appropriately. Here are some possible solutions.

## Read as string, convert if necessary

### `atoi`

The `atoi()` function takes a C-string parameter and converts it to an integer. This isn't a very nice function becuase it doesn't give any indication that there is an error.

       int i = atoi(cstring);

Here is an example that uses it. This uses the `string` class instead of an array of characters (C-string), so the `c_str()` member function has to be called to convert it to a C-string.

    string word;
    while (cin >> word) {
        if (isdigit(word[0])) {
            int i = atoi(word.c_str());
            cout << "integer " << i << endl;
        } else {
            cout << "string " << word << endl;
        }
    }

You might be "amused" to run this program with various input.

Input String | Integer value
--- | ---
0 | 0

## Peek to see if next character is numeric