【问题标题】:How to seperate numbers in a string如何分隔字符串中的数字
【发布时间】:2020-11-11 03:52:59
【问题描述】:
#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' 和 operator =' / ' 给运算符等等

【问题讨论】:

  • 是作业吗?可以询问您需要的更具体的部分,例如:“这个解决方案的部分应该是什么?”但目前听起来像是“你能帮我解决这个问题吗”。
  • 是的,这是作业,我不明白如何解析字符串来给我各个部分。
  • while 应替换为 for;i++ 之后不需要
  • @sravs 为什么我应该使用“for”而不是“while”
  • 您已经编写了三个部分(初始化;条件检查;更新),如forwhile 只进行部分条件检查,如 while(i &lt;= 5)

标签: c++ string data-structures


【解决方案1】:

由于这似乎是学生的家庭作业,我将为您提供另一种计算器的解决方案,您可以随意修改它;)

#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;
} }

【讨论】:

  • 我想你刚刚打开了我的第三只眼 lmao
【解决方案2】:

你可以借助strtok、strchr来解析字符串(分离出操作符号和两个数字操作数)。 要将 "34" 等数字字符串转换为 34 ,可以使用 atoi 和 atod 等函数。

【讨论】:

    猜你喜欢
    • 2012-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-06
    相关资源
    最近更新 更多