0
votes

I have the following code in C:

#include <stdio.h>
#include <stdlib.h>

int var();
int var()
{
    return 10;
}
 
void main()
{
    int a;
    double x;
    a=0;
    a=var();
    printf("hello world, i am a function which returned the value %d",a);
    printf("\nnow you enter a value:");
    scanf("%d",&a);
    
    printf("so you entered the value: %d",a);
    printf("\nnow enter a double value:");
    scanf("%lf",&x);
    printf("The double number till 4 precision is: %0.4lf",x);
}

When I input normal integer and double values for the two scanf it runs fine. However I want to make it more robust. If I enter a decimal value for int scanf the code jumps directly to the next printf and skips the scanf for double. It prints the decimal part that I have input in the int as the double value.

eg:

hello world, i am a function which returned the value 10

now you enter a value:44.67

so you entered the value: 44

now enter a double value:The double number till 4 precision is: 0.6700

Any help?

2
Read the manual page for scanf - it returns a value!Ed Heal
@EdHeal , But that won't help in this case as both the scanfs will return 1. Checking this is good,though...Spikatrix
When you input 44.67, the first scanf consumes 44. The second scanf sees the .67 and consumes it as it is a valid decimal number . This is why the second scanf gets "skipped"Spikatrix
Perhaps a better pattern for scanf is requiredEd Heal
Always check the return value of scanf, eg: if (scanf("%d", &a) != 1) /* error */;pmg

2 Answers

1
votes

It's tricky because a number with fractions (like e.g 12.34) do have a valid integer part, which is read and correctly parsed by the first scanf call.

The simplest solution is to use e.g. fgets to read the input into a buffer, and then use sscanf on that buffer.

1
votes

You should use the function fpurge() to erase any input or output buffered in the given stream (which is stdin in this case). Try this:

#include <stdio.h>
#include <stdlib.h>

int var();

int main(int argc, char *argv[]) {
  int a;
  double x;

  a = 0;
  a = var();

  printf("Hello world, I am a function which returned the value %d.\n", a);
  printf("Now you enter a value: ");
  scanf("%d", &a);

  printf("So, you entered the value %d.\n", a);
  printf("Now enter a double value: ");
  fpurge(stdin);
  scanf("%lf", &x);
  printf("The double number till 4 precision is %.4lf.\n", x);

  return 0;
} // End main

int var() {
  return 10;
}

Here is the output which I got:

Hello world, I am a function which returned the value 10.
Now you enter a value: 44.67
So, you entered the value 44.
Now enter a double value: 3.14159
The double number till 4 precision is 3.1416.