【问题标题】:c function getline includes the '\n' characterc函数getline包含'\n'字符
【发布时间】:2022-07-27 23:18:54
【问题描述】:

有没有办法在使用getline(&string, &len, stdin) 时不在我的字符串中输入换行符?或者有人知道从标准输入获取输入的方法? 我正在使用 C11 和 gcc 编译器

任何建议将不胜感激。

【问题讨论】:

  • string[strcspn ( string, "\n")] = 0; 可以在getline 之后使用以删除换行符。
  • @xing getline 方便地返回读取的字符数,因此无需使用strcspn 再次解析它

标签: c input stdin stdio c11


【解决方案1】:

自己写一个:

ssize_t meygetline(char **restrict lineptr, size_t *restrict n, FILE *restrict stream)
{
    ssize_t result = getline(lineptr, n, stream);
    if(result > 0) 
        if((*lineptr)[result - 1] == '\n') {(*lineptr)[result - 1]= 0; result--;}
    return result;
}

【讨论】:

  • 字符串的长度将与带有'\n'的字符串的长度相同?
  • 如果换行符被删除,你不需要递减result吗?
  • @Proth 是的,只是最后一个 \n 将被替换为 \0
猜你喜欢
  • 2012-04-23
  • 1970-01-01
  • 2015-03-23
  • 2019-03-13
  • 2010-11-12
  • 1970-01-01
  • 1970-01-01
  • 2012-09-10
  • 2018-11-11
相关资源
最近更新 更多