首页 > 解决方案 > 执行for循环

问题描述

这个循环将如何无限次执行?

#include <stdio.h>

int main() {
    int i;
    for (; scanf("%d", &i); printf("%d\n", i)); 
    return 0;
}

标签: cloops

解决方案


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));

推荐阅读