Removing a new line from fgets

I apologize if this question is obvious, or if I make a simple logical mistake. I have been looking for various ways to get rid of the new line that comes from using fgets, but I continue to run into problems when building. I think that I do not understand something correctly and incorrectly apply my "solution". I would like to be transparent and say that this is a school assignment. Everything works well, except for my output, which has unnecessary newlines.

The sole purpose of this function is to read names into an array of structures.

void initialize(FILE * ifp, Candidate * electionCandidates, int count)
{

for (int i = 0; i < count; i++)
{

    fgets (electionCandidates[i].name , 20 , ifp);

    if (electionCandidates[i].name[strlen(electionCandidates[i].name) - 1] == '\n')
    {
        electionCandidates[i].name[strlen(electionCandidates[i].name) - 1] = '\0';
    }   
} 
}

When trying to do the following: "Implicitly declares a library function" strlen "of type unsigned long (constant char *)"

+1
3

1) , "" - .

2) , "strlen()".

3) , #include <string.h> "strlen()".

#include <stdio.h>
#include <string.h>
...

char *trim (char *s) {
  int i = strlen(s)-1;
  if ((i > 0) && (s[i] == '\n'))
    s[i] = '\0';
  return s;
}
+2

.

#include <stdio.h>
#include <string.h> // to fix the warning
...

// remove NL left by fgets, with protection
void trimnl (char *s) {
  char *pnl = s + strlen(s);
  if (*s && *--pnl == '\n')
    *pnl = 0;
}

void initialize(FILE* ifp, Candidate* electionCandidates, int count) {
for (int i = 0; i < count; i++) {
    fgets (electionCandidates[i].name, 20, ifp);
    trimnl(electionCandidates[i].name);
  } 
}

  char *pnl = s + strlen(s) - 1;

. , ( strlen = 0) :

  char *pnl = s - 1;

, Undefined Behavior. .

0

-Wall, .

Depending on your compiler, you will receive useful tips on how to solve this and similar problems (which were discussed in one answer elsewhere in this thread), compiling with Clang will warn you about the missing one include, for example).

0
source

Source: https://habr.com/ru/post/1625751/


All Articles