C++ Standard Input Read only numbers

Description

C++ Standard Input Read only numbers

#include <iostream>
#include <sstream>
#include <conio.h>

using namespace std;

int StringToNumber(string MyString)
{
    istringstream converter(MyString); // Holds the string.
    int result;                        // Holds the integer result.

    // Perform the conversion.
    converter >> result;/*w  w w. ja v a 2s . c om*/
    return result;
}

string EnterOnlyNumbers()
{
    string numAsString = ""; // Holds the numeric string.
    char ch = getch();       // Obtains a single character from the user.

    // Keep requesting characters until the user presses Enter.
    while (ch != '\r')  // \r is the enter key
    {
        // Add characters only if they are numbers.
        if (ch >= '0' && ch <= '9')
        {
            cout << ch;
            numAsString += ch;
        }

        // Get the next character from the user.
        ch = getch();
    }
    return numAsString;
}

string EnterPassword()
{
    string numAsString = ""; // Holds the password string.
    char ch = getch();       // Obtains a single character from the user.

    while (ch != '\r')  // \r is the enter key
    {
        cout << '*';

        // Add the character to the password string.
        numAsString += ch;

        // Get the next character from the user.
        ch = getch();
    }

    return numAsString;
}

int main()
{
    string name;
    cout << "What is your name? ";
    cin >> name;
    cout << "Hello " << name << endl;

    // enter a number,
    // but allows you to enter anything!
    int x;
    cout << endl;
    cout << "Enter a number, any number! ";
    cin >> x;
    cout << "You chose " << x << endl;

    // you can only enter a number.
    cout << endl;
    cout << "This time you'll only be able to enter a number!" << endl;
    cout << "Enter a number, any number! ";
    string entered = EnterOnlyNumbers();
    int num = StringToNumber(entered);
    cout << endl << "You entered " << num << endl;

    // Now enter a password!
    cout << endl;
    cout << "Enter your password! ";
    string password = EnterPassword();
    cout << endl << "password:" << password << endl;
    return 0;
}



PreviousNext

Related