fgets

Removing trailing newline character from fgets() input

旧街凉风 提交于 2019-11-25 22:12:14
问题 I am trying to get some data from the user and send it to another function in gcc. The code is something like this. printf(\"Enter your Name: \"); if (!(fgets(Name, sizeof Name, stdin) != NULL)) { fprintf(stderr, \"Error reading Name.\\n\"); exit(1); } However, I find that it has a newline \\n character in the end. So if I enter John it ends up sending John\\n . How do I remove that \\n and send a proper string. 回答1: The slightly ugly way: char *pos; if ((pos=strchr(Name, '\n')) != NULL) *pos

fgets doesn't work after scanf

余生颓废 提交于 2019-11-25 21:48:36
问题 #include <stdio.h> #include <string.h> #include <ctype.h> void delspace(char *str); int main() { int i, loops; char s1[101], s2[101]; scanf(\"%d\", &loops); while (loops--) { fgets(s1, 101, stdin); fgets(s2, 101, stdin); s1[strlen(s1)] = \'\\0\'; s2[strlen(s2)] = \'\\0\'; if (s1[0] == \'\\n\' && s2[0] == \'\\n\') { printf(\"YES\\n\"); continue; } delspace(s1); delspace(s2); for (i = 0; s1[i] != \'\\0\'; i++) s1[i] = tolower(s1[i]); for (i = 0; s2[i] != \'\\0\'; i++) s2[i] = tolower(s2[i]); if