Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Objective-C
#include<stdio.h>
#include<conio.h>
#include<string.h>


struct est
{
int sno;
};

void main()
{
struct est s1;
char name[40];

printf("enter a number\n");
scanf("%d", &s1.sno);

printf("Name?\n");
fgets(name, 40, stdin);
getch();
}


I'm a complete noob in C and i really need help.
The first input goes fine, but after it prints Name? as soon as i press any key it either quits (in orange C IDE) or shows the equivalent ASCII (Pelles C, though I'm sure it is actually just quitting)
It works fine without me using the first scanf not sure why.
Any help is greatly appreciated :^)

What I have tried:

I have tried gets() too but in vain.
Posted
Updated 20-Jul-17 20:46pm

1 solution

That is beacuse your scanf() call reads the input without the new line character generated when pressing the ENTER key. So this new line character is still in the input buffer. The fgets() call will read from the input until a new line character is present. But that is already there and so it returns immediately.

This has been asked before and multiple answers and solutions can be found in the web like at c - fgets instructions gets skipped.Why? - Stack Overflow[^].

In general you should not use scanf() for keyboard input. It is better to write an input routine using fgets(), parse the string to check if it matches the required format, and convert it to the destination type upon success (e.g. using atoi() or strtol() for integers).
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900