Remove Trailing Newline Character From fgets() Input | C Programming Example

preview_player
Показать описание
Рекомендации по теме
Комментарии
Автор

This is a great tutorial to remove the trailing newline from fgets(), but this does not account for one edge case where the input exceeds the buffer size. For example, if the buffer size is 8 and the user inputs 8 or more characters, then the trailing newline character is not present. There are a few ways to deal with this issue, but here is one simple solution:

char userInput[8];
...
int length = strlen(userInput);
if (userInput[length - 1] == '/n'){
userInput[length - 1] = '/0';
length = length - 1;
}

vlogtomejr.
Автор

you are the best ... trust me your are the only video that actually solve my doubt in the entire youtube ... keep the work man lots of love from INDIA

kcsolgr
Автор

this helped a lot. I think i will combine this with an if statement if the user enters past the buffer amount “”i.e over-buffering attack” to check if there even is a trailing new line at all. from what i can gather, fgets() does not have a trailing new line if it runs out of buffer space and will instead end with the null terminator ‘\0’ at array[strlen(array)] & also a have a valid character you do not want overridden at array[strlen(array) - 1].

BLACKBERREST
Автор

Thank you sir, i found this method from other video but didn't understand it. After founding this video i finally understand it.

DeanT.
Автор

excellent, , you soleved my problem perfectly, , , , thanks a lot

farhanlabibahan
Автор

I was searching for the use of the getchar(); function in consuming newline character when I found your tutorial. Can the getchar(); function work in your example above instead of the approach you used?
(I'm a beginner at C 🙂)

Solomon_Ayuba
Автор

I’m wondering if this is why I was failing my tests on code chef. The problem was to take S = a string of lowercase letters. Than take N words and output yes if you can spell that word using letters from S. Originally I was using fgets and failed. I thought way too hard about it. Eventually I just looked at someone else’s answer and switched fgets to just using scanf(“ %s”, string) and it suddenly passed.

arthur_p_dent
Автор

Is there any possibility to do it with getc() ?
Actually I'm working on a program that reads bits from a file but the problem is that it also reads the newline character.

moadelhaddad
Автор

can't we use getch to remove the trailing character?

Sabari
Автор

what does
pragrma code name 0x08 do?

Rock-rkhh
Автор

i tried this code, it its working only for 8characters, whenever you enter a string more than 8, it is not workin, can you please help

db