0

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?

Azerty560
  • 125
  • 3
  • 15
  • I had to skim your question because lack of time, but did you mean to print "What is.."? if so you could just use printf and scanf together in the same line. – MasterMastic Apr 28 '13 at 12:10
  • 2
    What does the input look like in the general case? You need to define the problem before you can solve it. – interjay Apr 28 '13 at 12:44
  • Parsing free-form input in C is going to be painful, but have a look at [strtok()](http://man7.org/linux/man-pages/man3/strtok.3.html) ... or consider switching to a higher-lever language. – tripleee Apr 28 '13 at 12:54
  • The purpose of the program is akin to that of google calculator, you effectively can type in basic sums and the program solves it, irrespective of how you enter it. This can range from: What is x plus y; @interjay Add x and y; X + Y; Whatis x+y; etc. – Azerty560 Apr 28 '13 at 15:38
  • A higher level language? Like VB?:) – Azerty560 Apr 28 '13 at 15:43

1 Answers1

1

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.

Community
  • 1
  • 1
Ben Ruijl
  • 4,973
  • 3
  • 31
  • 44