I am trying to force the user to input a polynomial in the following format: (num)x^2+or-(num)x+or-(num)

I have labeled my error messages with 1 2 3 and 4. When I input something like 3204723094823094823094829, I do not get an error and I should, due to not finding "x^2" in the string.

istream& operator>> (istream& inp, Polynomial& poly) {

    bool isTrue = true;
    string temp;
    string tempCoef;
    unsigned pos;

    while(isTrue) {
        getline(inp, temp);

        if (!(pos = temp.find("x^2"))) {
            cout << "You have entered invalid input1" << endl;
            cin.clear();
            cin.ignore(10000, '\n');
            system("pause");
            continue;
        }
        tempCoef = temp.substr(0, pos);
        if (!(poly.coef[0] = atoi(tempCoef.c_str()))) {
            cout << "You have entered invalid input2" << endl;
            cin.clear();
            cin.ignore(10000, '\n');
            system("pause");
            continue;
        }

        temp.erase(0, pos+3);

        pos = temp.find("x");
        tempCoef = temp.substr(0, pos);
        if (!(poly.coef[1] = atoi(tempCoef.c_str()))) {
            cout << "You have entered invalid input3" << endl;
            cin.clear();
            cin.ignore(10000, '\n');
            system("pause");
            continue;
        }

        temp.erase(0, pos+1);

        tempCoef = temp;
        if (!(poly.coef[2] = atoi(tempCoef.c_str()))) {
            cout << "You have entered invalid input4" << endl;
            cin.clear();
            cin.ignore(10000, '\n');
            system("pause");
            continue;
        }

        isTrue = false;
    }

    return inp;

}

Recommended Answers

All 3 Replies

Change line 11 to

if (std::string::npos == (pos = temp.find("x^2"))) 

I am trying to understand what I did wrong?

I am trying to understand what I did wrong?

find does not return 0 when it doesn't find what it's looking for. It returns string::npos

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.