C ++ MFC将字符串数组的一部分转换为一个整数

时间:2015-09-25 09:49:39

标签: c++ calculator tokenize

这是问题所在。我正在尝试编写类似于所有计算机中的计算器的计算器。它应该从一个EditBox获取值,进行所有需要的计算,然后在另一个EditBox中显示。例如:3 * 6/2;结果:9; 我设法做到了:

double rezultatas = 0;
double temp = 0;
// TODO: Add your control notification handler code here
UpdateData(TRUE);
for (int i = 0; i < seka_d.GetLength(); i++)
{
    if (seka_d[i] == '/' || seka_d[i] == '*')
    {
        if (seka_d[i] == '*')
        {
            temp = (seka_d[i - 1] - '0') * (seka_d[i + 1] - '0');
        }
        if (seka_d[i] == '/')
        {
            temp = (seka_d[i - 1] - '0') / (seka_d[i + 1] - '0');
        }
        //temp = (seka_d[i - 1] - '0') / (seka_d[i + 1] - '0');

    }
    if (seka_d[i] == '+' || seka_d[i] == '-')
    {
        if (seka_d[i] == '-')
        {
            temp = (seka_d[i - 1] - '0') - (seka_d[i + 1] - '0');
        }
        if (seka_d[i] == '+')
        {
            temp = (seka_d[i - 1] - '0') + (seka_d[i + 1] - '0');
        }
        //temp = (seka_d[i - 1] - '0') + (seka_d[i + 1] - '0');

    }
    if (seka_d[i] == '-')
    {
        temp = (seka_d[i - 1] - '0') - (seka_d[i + 1] - '0');
    }

    //rezultatas++;
}
result_d = temp;
UpdateData(FALSE);

它检查字符串seka_d是否包含'*',' - ','/','+'这样的符号,并且使用两个相邻的符号(例如1 + 2,总和1和2)进行操作(我知道)它还没有正常运行多个操作),但现在我还要操作双打,所以我想知道是否可以将字符串的一部分转换为整数或双精度(例如0.555 + 1.766)。想法是从开始到符号(从开始到'+')和从符号到字符串的结尾或另一个符号(例如,如果字符串是0.555 + 1.766-3.445,它将占用字符串的一部分)的字符串的一部分'+'直到' - ')。有可能这样做吗?

1 个答案:

答案 0 :(得分:1)

您可以使用CString::Tokenize https://msdn.microsoft.com/en-us/library/k4ftfkd2.aspx

或转换为std::string

std::string s = seka_d;

以下是MFC示例:

void foo()
{
    CStringA str = "1.2*5+3/4.1-1";
    CStringA token = "/+-*";

    double result = 0;
    char operation = '+'; //this initialization is important
    int pos = 0;
    CStringA part = str.Tokenize(token, pos);
    while (part != "")
    {
        TRACE("%s\n", part); 
        double number = atof(part);

        if (operation == '+') result += number;
        if (operation == '-') result -= number;
        if (operation == '*') result *= number;
        if (operation == '/') result /= number;

        operation = -1;
        if (pos > 0 && pos < str.GetLength())
        {
            operation = str[pos - 1];
            TRACE("[%c]\n", operation);
        }

        part = str.Tokenize(token, pos);
    }

    TRACE("result = %f\n", result);
}

注意,这不处理括号。例如a*b+c*d((a*b)+c)*d Window的计算器做同样的事情。

相关问题