Computer Science, asked by khanammarowa, 7 months ago

what problem will arise when take input in a character variable after another input. how can you solve this problem? Explain with a suitavle example.​

Answers

Answered by AkashKumar372
4

Consider below simple program in C. The program reads an integer using scanf(), then reads a string using fgets().

// C program to demonstrate the problem when

// fgets()/gets() is used after scanf()

#include<stdio.h>

int main()

{

int x;

char str[100];

scanf("%d", &x);

fgets(str, 100, stdin);

printf("x = %d, str = %s", x, str);

return 0;

}

Input

10

test

Output:

x = 10, str =

The problem with above code is scanf() reads an integer and leaves a newline character in buffer. So fgets() only reads newline and the string “test” is ignored by the program.

The similar problem occurs when scanf() is used in a loop.

Mark my answer as a brainlist

Similar questions