Having the User Type Something, convert string to number - C++ Data Type

C++ examples for Data Type:string

Description

Having the User Type Something, convert string to number

Demo Code

#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;//from ww w.  j  a  v  a2  s .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;
}

Result


Related Tutorials