c - 在循环中一起使用 printf 和 fgets
问题描述
我正在尝试实现一个简单的程序,它可以无限地读取用户的输入,然后打印出来。但也有一些问题。这是一个简单的问题,但我的谷歌搜索并没有为我提供任何解决方案。这是代码。
int main() {
char pass[32];
int x=10;
while (x!=0) {
printf("\nInput the password: ");
fgets(pass, sizeof(pass), stdin);
printf("that is what i read: %s", pass);
}
return 0;
}
当我输入一个超过 32 个字符的字符串时,它的行为异常。
Input the password: pass
that is what i read: pass
Input the password: passsssss
that is what i read: passsssss
Input the password: passssssssssssssssssssssssssssssss
that is what i read: passsssssssssssssssssssssssssss
Input the password: that is what i read: sss
Input the password:
您在第三次尝试中看到,它会自动打印第三行。我没有输入“这就是我读到的内容:sss”。
为什么会这样?
解决方案
fgets()
不限制用户输入的行的长度。 fgets()
限制读取该行的多少。
输入过多,剩余部分留给下一个输入操作。
如果输入 viafgets()
缺少 a '\n'
,则要么
- 整行没有读完,(很常见)
- 输入 w/o
'\n'
然后结束文件,(很少) - 读取了一个空字符。(稀有的)
- 输入缓冲区小于 1。(病态)
下面很容易识别前 2 个。
// Test if anything was read.
if (fgets(pass, sizeof pass, stdin)) {
// Was it missing a '\n'?
if (strchr(pass, '\n') == NULL) {
// Read rest of line and throw it away
int ch;
while ((ch = fgetc(stdin)) != '\n' && ch != EOF) {
;
}
}
}
推荐阅读
- scikit-learn - 当我从管道中删除 RF 模型时,它会失去准确性
- react-native - 评级不选择超过 3 星 - React Native Elements - 评级)
- html - 关于如何使用纯 CSS 制作这个的任何想法?文本剪辑到背景图像
- django - 如何将文件从 Angular 7 上传到 Django - 得到错误 403(禁止)
- python - 比较列表中的多个列表
- javascript - 如何在站点和第三方 Javascript 小部件之间实施用户管理?
- php - 网上商店需要添加到购物车按钮对齐
- javascript - 在javascript中达到特定数字时如何从x++到x--间隔?
- python - 遍历 Python 中的字符串列表
- java - JInternalFrame - 非法组件位置