Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Scanf input testing for expected input format

I need to make a simple C program which will solve quadratic equation in expected format that needs to be like this:

a x^2 + b x + c = d x^2 + e x + f

I'm using scanf to read the input, and it works as expected. But I need to implement some input testing for my scanf reading which is like that right now:

scanf("%f x^2 + %f x + %f = %f x^2 + %f x + %f", &a, &b, &c, &d, &e, &f);

I need to printf("Wrong input\n"); for every input like f.e.

'abc', '1 x^2 + 1 x + 1 = 0', 'x^3...'

I tried the if (scanf() != 1), but it prints the 'Wrong output' every time. Any ideas about how can I accomplish that?

like image 655
jirick Avatar asked Dec 04 '25 00:12

jirick


1 Answers

if I enter only '1 x^2 + 1 x + 1 = 0' it waits for next possible input.

In that case read complete input using fgets and parse the values using sscanf as below.

  char buf[100];
  fgets(buf,sizeof buf,stdin);

  int r = sscanf(buf,"%f x^2 + %f x + %f = %f x^2 + %f x + %f", &a, &b, &c, &d, &e, &f);
  if (r!=6)
     printf("Wrong input\n");
  else
     printf("correct\n");
like image 186
kiran Biradar Avatar answered Dec 05 '25 15:12

kiran Biradar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!