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

C++ MFC Converting part of string array into one integer

本文关键字:一个 整数 数组 字符串 一部分 转换      更新时间:2023-10-16

问题在这里。我试着写一个类似于所有计算机的计算器。它应该从一个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,它将从'+'到'-'取字符串的一部分)。可以这样做吗?

您可以使用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("%sn", 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 = %fn", result);
}

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

相关文章: