Yariz
Yariz

Reputation: 3

How to get two inputs from a same input (C++)

Title probably sounds confusing so first I'll show you my code, I made this simple program to get two input values and multiply them, and another thing, but that's not important, It works correctly:

#include <iostream>

using namespace std;

main()
{
    int a,b,c,d,e;
    char j = 4;
    cout << "Welcome to Momentum Calculator\n\n";
    cout << "------------------------------\n";
    cout << "Please Enter Mass in KG (if the mass in in grams, put \"9999\" and hit enter): \n\n";
    cin >> a;
    if (a==9999) {
        cout << "\nPlease Enter Mass in grams: \n\n";
        cin >> d;
    }
    else {
        d = 0;
    }
    cout << "\nPlease Enter Velocity \n\n";
    cin >> e;
    if (d == 0)
    {
        c = (a*e);
    }
    else {
        c = (e*d)/100;
    }
    cout << "\nMomentum = " << c;
    cin.get();
    cin.ignore();
    while (j == 4)
    {
        cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
        main();
    }
}

Now as you can see, my variable is an int (integer) and my problem is If I enter an English letter (a-z) or anything that is not a number will cause it to repeat my program unlimited times at an unlimited speed. I want a string/char to see if my var "a" is a letter or anything but don't know how to. I can do it, however, I want user to input only one time in "a" and mine makes him to enter again. Please Help :)

Upvotes: 0

Views: 576

Answers (3)

KKas
KKas

Reputation: 5

Will isdigit or isalpha from standard library help you?

P.S. 1KG contains 1000 grams, so you should divide by 1000, not by 100;

UPDATE: Seems I understood your question... You need cin.clear(); before cin.get() and cin.ignore(). Otherwise the these calls won't do anything, as cin is in an error state.

Upvotes: 1

TheHost
TheHost

Reputation: 45

There is a function called isalpha in ctype library, checks whether your variable is an alphabetic letter so you can do using isalpha function.

Upvotes: 1

I think you can get a as an String, and see if it contains English letter or not, if it contains, again ask for the input ( you can do it in a while loop ). And when a correct input entered, parse it and find what is it's number.

Upvotes: 0

Related Questions