c - 执行for循环
问题描述
这个循环将如何无限次执行?
#include <stdio.h>
int main() {
int i;
for (; scanf("%d", &i); printf("%d\n", i));
return 0;
}
解决方案
for
循环的条件部分是scanf("%d", &i);
在用户提供无效输入之前返回真。读取man 3 scanf
并检查返回值。
更好的运行循环,直到你按下键Ctrl+d
for (; scanf("%d", &i) != EOF; printf("%d\n", i));
或者比较 ,as 的返回值scanf()
,scanf("%d", &i) == 1
只要1
它能够将用户输入转换为整数即可。
for (; scanf("%d", &i) == 1; printf("%d\n", i));
推荐阅读
- java - 如何在android的firebase数据库中为动态键和值创建模型类
- mysql - 如何与第一个匹配行左连接并用空填充其余部分?
- list - 变量“@{credentials}[0]”的值不是列表或类似列表
- python-3.x - python使用vpn时,urllib3 connect报错“SSLEOFError: EOF发生违反协议(_ssl.c:1129)”
- visual-studio-code - 如何重置 VS Code 的窗口缩放设置?
- reactjs - 从 sanity io 数据库中提取时,部分图像不会显示
- ngrx - dom 不反映使用 onPush 策略和 ngrx 商店订阅的实际值
- html - HTML 表格不会在 iPhone 上垂直滚动
- arrays - Javascript对二维数组进行排序
- reactjs - 在 MUI 中使用可变字体的优雅方式