0

I'm new to c++ so please be patient.

I want my program to check if input isn't of type float and if it is, the program should return an error to the user. I tried using cin.fail() and cin.good() but it didn't work when the input was e.g. "123abc".

Another problem is: my input can't be decimal because "." isn't numeric. What can I do? Here is my code:

    int maint(void)
    {
        bool czy_to_liczbaa;
        bool czy_to_liczbab;
        stringstream s1;
        stringstream s2;
        string liczbaa;
        string liczbab;
        float a;
        float b;

        do
        {
            czy_to_liczbaa = true;
            cout<<"Enter first number"<<endl;
            cin>>liczbaa;
            for(int i=0;i<liczbaa.length();i++)
            {
                if(!isdigit(liczbaa[i])&&liczbaa>>a;)
                czy_to_liczbaa = false;
            }
            if(!czy_to_liczbaa)
                cout<<"This isn't a number!"<<endl;
        }while(!czy_to_liczbaa);

        s1 << liczbaa;
        s1 >> a;
        s1.clear();

       do
       {
            czy_to_liczbab = true;
            cout<<"Enter second number: "<<endl;
            cin>>liczbab;
            for(int i=0;i<liczbab.length();i++)
            {
                if(!isdigit(liczbab[i]))
                    czy_to_liczbab = false;
            }
            if(!czy_to_liczbab)
                cout<<"This isn't a number!"<<endl;
        }while(!czy_to_liczbab);

        s2 << liczbab;
        s2 >> b;
        s2.clear();
        float suma = a + b;
        cout<<"a + b = "<<suma<<endl;

     return 0;
     }
jjj
  • 1,067
  • 1
  • 15
  • 30
  • 9
    So [this answer doesn't work for you](https://stackoverflow.com/questions/29169153/how-do-i-verify-a-string-is-valid-double-even-if-it-has-a-point-in-it)? Also, if you found yourself writing all of this code to verify if a string is a double, you should have stopped and said to yourself "this can't be right. There must be a simple way to find this out". – PaulMcKenzie Dec 19 '17 at 22:35
  • 1
    Possible duplicate of [How do i verify a string is valid double (even if it has a point in it)?](https://stackoverflow.com/questions/29169153/how-do-i-verify-a-string-is-valid-double-even-if-it-has-a-point-in-it) – user3486184 Dec 19 '17 at 23:04

0 Answers0