2015-09-25 139 views
1

这是问题所在。我试图写一个类似于所有电脑中的计算器。它应该从一个EditBox获取值,进行所有需要的计算,然后显示在另一个EditBox中。例如:3 * 6/2;结果:9; 我已经成功地做到这一点:C++ MFC将字符串数组的一部分转换为一个整数

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像“*”,任何simbols“ - ”,“/”,“+”和做有两个邻居simbols(前操作。1 + 2,总和1和2)(我知道它不能正常工作与多个操作),但现在我必须也与双打操作,所以我想知道是否有可能将字符串的一部分转换为整数或双倍(例如0.555 + 1.766)。想法是将字符串的一部分从开始到符号(从开始到'+'),从符号开始到字符串或另一个符号的末尾(例如,如果字符串是0.555 + 1.766-3.445,它将从字符串的一部分'+'直到' - ')。这样做有可能吗?

+0

这个问题与MFC技术无关,所以我删除了该标签,并添加了另一个更适合该问题的标签。 – Dialecticus

回答

1

您可以使用CString::Tokenizehttps://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窗口的计算器做同样的事情。

相关问题