I'm trying to make a program in C++ where the user will input an equation, (e.g.: y = 3x + 6). How would I determine what's a Value, and what's a Character, and where they are?

So from the example, I would know that:

  • Value 3 is at position stringArray[4]
  • Value 6 is at position stringArray[9]
  • Character x is at position stringArray[5]

How would I write this?

When I enter y = 3x in visual studio 2013, it comes up with an error box:

Unhandled exception at 0x77662EEC in Graphmatica_WhatsInDatInput.exe: Microsoft C++ exception: std::invalid_argument at memory location 0x00FAF94C.

but when I enter anything that is not starting with a character, it's fine (e.g. 1 + 3x)

This is my code so far:

#include <iostream>
#include <string>

using namespace std;

int main(){

    string Equation;
    double dNumber;

    cout << ": ";
    getline(cin, Equation);


    for (int i = 0; i < Equation.size(); i++){
        if (isdigit(Equation[i])) {
            cout << "Number: ";
            dNumber = stod(Equation);
            cout << dNumber << endl;

        }
        else {
            if (Equation[i] != ' ') {
                cout << "Character" << endl;
            }
        }
    }

    cout << endl;
    system("pause");
}
有帮助吗?

解决方案

Your error is because of this line:

dNumber = stod(Equation);

Its exception documentation says: If no conversion could be performed, an std::invalid_argument exception is thrown.

When you entered a letter, no conversion could be performed and you got the exception.

Secondly, you're trying to convert the entire equation to a double.. If that is the case, what was the point of checking if each index in the string is a digit?

I think you meant to put: stod(to_string(Equation[I])) instead..

You can also create your own conversion functions using the ones already provided for you in C.

#include <iostream>
#include <string>

using namespace std;

inline double strtodouble(char c) noexcept
{
    return strtod(&c, NULL);
}

inline double strtodouble(const char* str) noexcept
{
    return strtod(str, NULL);
}

inline double strtodouble(const std::string str) noexcept
{
    return strtod(str.c_str(), NULL);
}


int main()
{

    string Equation;
    double dNumber;

    cout << ": ";
    getline(cin, Equation);


    for (int i = 0; i < Equation.size(); i++)
    {
        if (isdigit(Equation[i]))
        {
            cout << "Number: ";
            dNumber = strtodouble(Equation[i]);
            cout << dNumber << endl;

        }
        else
        {
            if (Equation[i] != ' ')
            {
                cout << "Character" << endl;
            }
        }
    }

    cout << endl;
    system("pause");
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top