从字符串中提取整数

时间:2013-04-28 11:54:57

标签: c gcc

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

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

想法?

1 个答案:

答案 0 :(得分:1)

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

相关问题