c - 做 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);
有什么不足或者可以改进的地方吗?
解决方案
文件输入/输出是时间的后穴。使用宏而不是干净的函数几乎没有什么收获。
也许还有一个功能来做提示?
代码根据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;
}
推荐阅读
- vb.net - 在 MS Access 数据库中选择最大值
- excel - 为什么我的条件格式在工作表中工作时会失败?可能的间接问题?
- javascript - 如何通过 JSON 将表格数据从 HTML 前端传递到 Django 中的服务器端?
- java - 在java中通过SQL查询进行文本提取(分类)的最佳方法
- python - 在每一步从列表中切片大小为 N 的窗口
- java - 在单元测试中使用单例类获取 ExceptionInInitializerError
- angular - 如果localStorage item为null,设置item,否则返回Observable中的item?
- javascript - 如何从一些谷歌地图标记打开网络链接?
- node.js - Mongoose:完全删除文档和所有引用
- python - 在 Python 矩阵算法中修改列表