宏做fgets剥离换行符 [英] Macro to do fgets stripping newline

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

问题描述

给出以下两个语句以使用 fgets 并删除换行符:

Given the following two statements to use fgets and strip the newline:

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

下面的宏足以代替它吗?

Is the following macro sufficient to take the place of this?

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

是否有任何不足或方法可以改进?

Are there any deficiencies or ways it can be improved?

推荐答案

通常,我在(0); 技巧时执行 do {}.

Usually, I do the do { } while (0); trick.

但是,如果您想要一个可以代替 fgets 的宏,可以在其中透明地测试返回值,该怎么做:

But, if you want a macro that is a drop in replacement for fgets where you can test the return value transparently, how about:

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

#define FGETS(_buf,_len,_xf) \
    ({ \
        char *_cp = fgets(_buf,_len,_xf); \
        if (_cp != NULL) \
            _buf[strcspn(_buf,"\n")] = 0; \
        _cp; \
    })

#define FGETOF(_buf,_xf) \
    FGETS(_buf,sizeof(_buf),_xf)

int
main(void)
{
    char buf[100];

    while (1) {
        if (FGETOF(buf,stdin) == NULL)
            break;
        printf("buf: '%s'\n",buf);
    }

    return 0;
}


多行宏很好,但是可以使用 inline 函数清理[不损失速度]:


The multiline macro is fine, but can be cleaned up [with no loss in speed] using an inline function:

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

static inline char *
xfgets(char *buf,size_t siz,FILE *xf)
{
    char *cp;

    cp = fgets(buf,siz,xf);

    if (cp != NULL)
        buf[strcspn(buf,"\n")] = 0;

    return cp;
}

#define FGETS(_buf,_len,_xf) \
    xfgets(_buf,_len,_xf)

#define FGETOF(_buf,_xf) \
    FGETS(_buf,sizeof(_buf),_xf)

int
main(void)
{
    char buf[100];

    while (1) {
        if (FGETOF(buf,stdin) == NULL)
            break;
        printf("buf: '%s'\n",buf);
    }

    return 0;
}

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

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