Azerty560
Azerty560

Reputation: 125

Extracting Integers from Strings

I am trying to create a program which can 'read' input into two integers. E.g.

What is 20 plus 20

The program has to 'read' the 20 and 20. I have tried to use sscanf but it is extremely specific, e.g.

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

But this effectively relies on the user entering exactly "What is x plus y". I have tried using atoi but to no avail.

Code (for the relevant functions):

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

The following is for 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;
    }
}
}

Ideas?

Upvotes: 0

Views: 90

Answers (1)

Ben Ruijl
Ben Ruijl

Reputation: 5123

You could use strtok to split up the string into tokens. Then you can use strtod to try and convert each token to a number. You can check the second argument of strtod to see if the conversion succeeded. If it does, you can add the number to a list.

Upvotes: 1

Related Questions