从fgets删除换行符 [英] Removing newline from fgets

查看:246
本文介绍了从fgets删除换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,如果这个问题很明显,或者我犯了一个简单的逻辑错误.我已经寻找了各种方法来摆脱使用fgets产生的换行符,但是在构建过程中我仍然遇到问题.我认为我没有正确地理解某些东西,并且错误地应用了我的解决方案".我想保持透明,说这是学校的任务.除了我的输出(一切都没有必要的新行)之外,其他所有东西都运行良好.

I am sorry if this question is obvious, or if I am making a simple logic mistake. I have searched for various ways of getting rid of the newline that comes from using fgets, but I continue running into problems while building. I think I am not understanding something properly and applying my "solution" incorrectly. I would like to be transparent and say that this is an assignment for school. Everything runs well except my output, which has unnecessary new lines.

此功能的唯一目的是将名称读入结构数组中.

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

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';
    }   
} 
}

当我尝试运行时,显示以下内容:隐式声明类型为unsigned long(常数char *)的库函数"strlen""

The following is displayed when I attempt to run: "Implicitly declaring library function "strlen" with type unsigned long (constant char*)"

推荐答案

1)不,不一定显而易见"-好问题.

1) No, not necessarily "obvious" - good question.

2)是,您要使用"strlen()".

2) Yes, you want to use "strlen()".

3)听起来您好像忘记了#include <string.h>来定义"strlen()".

3) It sounds like you forgot #include <string.h> to defined "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;
}

这篇关于从fgets删除换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆