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

int main()
{
    int intvar=0; //variable to store integer input
    double decimalvar = 0; //variable to store double input
    char string[30]; //arrary to store string

    scanf("%d",&intvar); //scan for int input
    scanf("%f",&decimalvar); //scan for double input
    scanf("%[^\n]",string); //scan for a line input

    printf("%d\n",intvar); //print int var
    printf("%.1f\n",decimalvar);//print double var
    printf("%s",string);//print string

    return 0;
}

The program runs successfully, but it only takes two input. After entering the second input, the third scanf statement is skipped and the printf statements are executed. Why does this happen?

nalzok
  • 14,965
  • 21
  • 72
  • 139

3 Answers3

1
scanf("%f",&decimalvar); 

should be:

scanf("%lf",&decimalvar); 

because you're passing a double not a float.

This is technically undefined behavior, but is not the cause of your problem, which is that a newline is left in the stdin buffer after the scanf calls. Specifiers like d, f, lf consume and ignore that newline. Of course the specifier [^\n] finds that newline and stops reading while leaving some input in the stdin buffer.

To solve the problem add a space at the start of the scanf format string, which will consume the newline, before trying to read the stdin.

scanf(" %[^\n]",string);
2501
  • 25,460
  • 4
  • 47
  • 87
1

After every scanf() statement is executed, a '\n' is left in stdin. When executing scanf("%[^\n]", string);, that '\n' immediately causes a matching failure ("%[^\n]" expects all characters other than '\n'), so scanf() sadly returns.

To fix this, simply add a leading space in the format string to discard all (0 or more) whitespace characters, like this:

scanf(" %[^\n]", string);

A few unrelated tips:

  1. Change scanf("%f", &decimalvar); to scanf("%lf", &decimalvar); to avoid undefined behaviour. See Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?
  2. Use fgets(string, sizeof string, stdin) to prevent the potential buffer overflow.
Community
  • 1
  • 1
nalzok
  • 14,965
  • 21
  • 72
  • 139
0
scanf("%[^\n]",string);  

should be

scanf("%s",string);