如何在字符串中分隔数字

How to seperate numbers in a string

本文关键字:分隔 数字 字符串      更新时间:2024-09-23
#include<iostream>
#include<cmath>
#include<string>
#include<fstream>
using namespace std;    
struct Calculations //structure to hold the numbers and operators from 'equation' 
{
double num1;
char   operators;
double num2;
double answer;
};
Calculations myCalculationArray[SIZE]; // the array of calculations
int main()
{

while (i = 0; i <= 5; i++;)
{
cout << "Enter equation: n";
getline(cin, equation);
cout << equation;
}
}

好吧,所以我试图建立一个计算器,用户在其中输入一个方程;22/2";,然后将第一个数字分配给num1='22',将运算符='/'分配给运算符等。

由于这似乎是学生的家庭作业,我将为您提供另一个计算器解决方案,您可以根据自己的喜好进行修改;(

#include<iostream>
#include<cmath>
using namespace std;    

int main() {
char op;
float num1, num2;
cout << "Enter two operands: ";
cin >> num1 >> op >> num2;
switch(op)
{
case '+':
cout << num1+num2;
break;
case '-':
cout << num1-num2;
break;
case '*':
cout << num1*num2;
break;
case '/':
cout << num1/num2;
break;
default:
// If the operator is other than +, -, * or /, error message is shown
cout << "Error! operator is not correct";
break;
} }

您可以借助strtok、strchr来解析字符串(分离出运算符号和两个数字操作数(。为了将诸如";34〃;到34,你可以使用atoi和atod等功能。