I've read many threads on how to remove a new line character '\n' using fgets()-- however, how would one go about removing a new line character simply by using getchar() ?
dbsp 0 Newbie Poster
Recommended Answers
Jump to PostWell I got it to work... try commenting out the while loop and it skips the fgets
#include<stdio.h> int main(void){ char name[30]; int c,r; printf("Enter number"); scanf("%d", &r); while ((c = getchar()) != '\n' && c != EOF); printf("Enter name"); fgets(name,sizeof(name),stdin); return 0; }
Jump to PostGet rid of that complex FOR statement. Doing 2
fgets()
in a FOR statement is a recipe for disaster. Keep your code simple.
Pull those 2 reads out and put them in the loop itself.
Jump to PostThe problem is not with fgets() reading a newline character, it's with scanf() leaving a newline character in the stream for fgets() to read. To fix the problem, change how you're using scanf(), or use a different method of input.
There are two common recommendations. First, you can avoid …
All 11 Replies
zeroliken 79 Nearly a Posting Virtuoso
dbsp 0 Newbie Poster
zeroliken 79 Nearly a Posting Virtuoso
dbsp 0 Newbie Poster
zeroliken 79 Nearly a Posting Virtuoso
dbsp 0 Newbie Poster
zeroliken 79 Nearly a Posting Virtuoso
dbsp 0 Newbie Poster
zeroliken 79 Nearly a Posting Virtuoso
WaltP 2,905 Posting Sage w/ dash of thyme Team Colleague
deceptikon 1,790 Code Sniper Team Colleague Featured Poster
zeroliken commented: I wasn't familiar with the first one so thanks for posting +8
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.