- 论坛徽章:
- 5
|
回复 105# pmerofc
我也不知道诶~~
我基本会把循环交给“下个层次”的语言来做,因为它们更有可能实现SIMD。所以我倾向于能用fgets就不用getchar,除非你需要的功能比fgets更少,从而手写会比SIMD加速版本更快。
另外i,getchar的话,依然是实现几乎跟fgets完全一致的功能,仅仅是省下了strlen和把'\n'改成'\0'的if。但是你得写成一个循环,处理正常字符和EOF,对对应指针进行赋值,最终添加一个'\0',最终结果可能并不能简单多少。也不能减少多少代码。
就输入而言。如果不知道格式,单纯只想要一行的话,用malloc+realloc动态分配几乎是肯定的。要健壮这个逃不掉。如果知道格式可以通过提前分析格式降低需要处理的字符数量。比如scanf直接给出%d这种模式。如果用malloc+realloc的话,fgets是最简单的选择了……
最好的办法是你的程序能直接接受输入。
lua.c(工业级的应用了)里面关于输入是这么做的:- /*
- ** lua_readline defines how to show a prompt and then read a line from
- ** the standard input.
- ** lua_saveline defines how to "save" a read line in a "history".
- ** lua_freeline defines how to free a line read by lua_readline.
- */
- #if defined(LUA_USE_READLINE)
- #include <stdio.h>
- #include <readline/readline.h>
- #include <readline/history.h>
- #define lua_readline(L,b,p) ((void)L, ((b)=readline(p)) != NULL)
- #define lua_saveline(L,idx) \
- if (lua_rawlen(L,idx) > 0) /* non-empty line? */ \
- add_history(lua_tostring(L, idx)); /* add it to history */
- #define lua_freeline(L,b) ((void)L, free(b))
- #elif !defined(lua_readline)
- #define lua_readline(L,b,p) \
- ((void)L, fputs(p, stdout), fflush(stdout), /* show prompt */ \
- fgets(b, LUA_MAXINPUT, stdin) != NULL) /* get line */
- #define lua_saveline(L,idx) { (void)L; (void)idx; }
- #define lua_freeline(L,b) { (void)L; (void)b; }
- #endif
复制代码 完全没有管'\n',因为Lua本身自己能处理程序中出现的空白符…… |
|