0

How do i properly see how many inputs were read in my scanf function? when i run the below code it does not display the result, is this because i dont have 2 inputs read from scanf or some other reason here is my code:

#include <stdio.h> 

int main()
{
float numberOne;
float numberTwo;

scanf("%f %f", &numberOne, &numberTwo);
float result = numberOne + numberTwo;

int howManyRead = scanf("%f %f", &numberOne, &numberTwo);

if ( howManyRead == 2)
{
    printf("%f", &result);
}   
else
{
    printf("invalid input");
}
sleep(10);

}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Squidly
  • 49
  • 2
  • https://stackoverflow.com/questions/10469643/value-returned-by-scanf-function-in-c Hope this can help. – marko Oct 18 '17 at 14:47
  • 2
    Did you mean to call scanf twice? – user2867342 Oct 18 '17 at 14:47
  • "how many inputs were read in my scanf function?" --> How do you want to the user to indicate that input is complete? By entering text and then a `'\n'`? Should input `"123\n"` report only 1 number was entered or wait for the next line of input like `"456\n"`? – chux - Reinstate Monica Oct 18 '17 at 15:19

2 Answers2

1

You have two calls of scanf in your code. The result of the first call is ignored, while the result of the second one is checked.

When you enter two numbers, the first scanf returns 2, which your code ignores. After that the call to second scanf tries to read two additional numbers.

You can fix this by removing the first call to scanf:

float numberOne, numberTwo;
if ( scanf("%f %f", &numberOne, &numberTwo) == 2) {
    float result = numberOne + numberTwo;
    printf("%f", result);
} else {
    printf("invalid input");
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
-1

You are not using the return value of scanf() in the expected way. It is there to indentify the success / failure in scanning and take a decision based on that.

There are three things you need to do.

  • Remove the two lines

    scanf("%f %f", &numberOne, &numberTwo); 
    float result = numberOne + numberTwo;
    

    This is because, without a check, if you try to use the destination variables, there values may be indeterminate in case scanf() fails. Also, there are repeated scanf()s which are plain wrong and not needed.

  • Add the line float result = numberOne + numberTwo; inside the condition block if ( howManyRead == 2).

  • Remove the & from the printf call: printf("%f", result);

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261