0

我正在尝试创建一个可以将输入“读取”为两个整数的程序。例如

What is 20 plus 20

该程序必须“读取” 20 和 20。我曾尝试使用 sscanf 但它非常具体,例如

int a; int b;
sscanf(INPUT, "What is %i plus %i" , &a, &b)

但这实际上依赖于用户准确输入“什么是 x 加 y”。我曾尝试使用 atoi 但无济于事。

代码(用于相关功能):

    int main()
{

while(1)
{
takeInput();
PERFORMED_CALC = calcToPerform(); //PERFORMED_CALC checks the operation to perform, e.g. + , -, x or /
printf(" = %i\n", performCalculation()); //PerformCalculation Interprets and solves any sums
}

return 0;
}

以下是针对 performCalculation() 的:

int performCalculation()
{
int a = 0; int b = 0;


switch(PERFORMED_CALC)
{
    case 1: 
    {
    sscanf(INPUT, "What is %i plus %i", &a,&b);
    return a+b;
    break;
    }
}
}

想法?

4

1 回答 1

1

您可以使用strtok将字符串拆分为标记。然后您可以strtod尝试将每个令牌转换为数字。您可以检查 的第二个参数strtod查看转换是否成功。如果是这样,您可以将号码添加到列表中。

于 2013-04-28T12:44:35.363 回答