首页 > 解决方案 > 做 fgets 剥离换行符的宏

问题描述

给定以下两个语句来使用fgets和去除换行符:

puts("Enter the name.");
fgets(temp.name, 40, stdin);
temp.name[strcspn(temp.name, "\n")] = 0;

以下宏是否足以代替它?

#define FGETS(str, len)  fgets(str, len, stdin); str[strcspn(str, "\n")] = 0
FGETS(temp.name, 40);

有什么不足或者可以改进的地方吗?

标签: cc-preprocessor

解决方案


文件输入/输出是时间的后穴。使用宏而不是干净的函数几乎没有什么收获。

也许还有一个功能来做提示?

代码根据C2x 原则使用领先的大小。

char *getaline(int size, char *s, const char *prompt) {
  if (prompt) {
    fputs(prompt, stdout);
  }
  if (fgets(s, size, stdin)) {
    // Perhaps add detection of failing to read the whole line?

    s[strcspn(s, "\n")] = '\0';
    return s;
  }
  if (size > 0) {
    *s = '\0';
  }
  return NULL;
}

推荐阅读