将字符串数组的一部分转换为一个整数
C++ MFC Converting part of string array into one integer
问题在这里。我试着写一个类似于所有计算机的计算器。它应该从一个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
窗口的计算器做同样的事情。
相关文章:
- C++需要帮助从用户那里获得一个整数,并确保它在另外两个整数之间
- 当我们从/tp地址中添加/减去一个整数时会发生什么
- 如何将一个数组值合并为一个整数c++
- 为什么有时我输入一个整数,程序将第一个输入的数字打印成十进制数?
- 给定一个整数数组,需要在Max_Heap上运行操作。得到错误"segmentation fault",有什么想法吗?(C++)
- 我可以将迭代器递增一个整数吗?
- 有没有办法生成一个包含平方的序列,这些平方加起来就是一个整数平方?
- 为什么将两个浮点数相加会得到一个整数C++?
- 如果我们在其中输入一个整数,则字符会给出整数作为输出,但是当分配给它一个整数时,这不会发生。为什么?
- 给枚举一个整数,并在 C++ 中将其相关值作为字符串获取
- 按升序输出整数时,将最后一个整数放在新行上
- 编写一个程序,提示用户输入一个整数,然后输出数字的单个数字和数字的总和
- 给定一个整数 N>0,区间 [0, 2^N) 中有多少个整数正好有 N-1 个设置位?编写一个返回正确答案的简短函数
- 给定一个整数,将其表示为平方和
- c++interpret_cast是一个整数
- 以最少的步骤将给定整数转换为另一个整数
- 当 map 是一个整数数组并且由 operator[] 创建时,它是否初始化其映射类型
- 我需要将字符串(例如 A5)转换为一个字符串 (A) 和一个整数 (5)
- 如何交替从文件中获取一行数据和一个整数?
- 如何让这个C++代码从用户那里读取五个整数而不是一个整数?