[英]Possible output of the following program fragment?
for(i=getchar();; i=getchar())
if(i=='x')
break;
else putchar(i);
Answer is : mi答案是:mi
Can someone explain this piece of code ?(MCQ Question)有人可以解释这段代码吗?(MCQ问题)
This question can be solved by eliminating incorrect answer.这个问题可以通过消除错误答案来解决。 This fragments prints character and exits loop if the character is an
x
.如果字符是
x
则此片段打印字符并退出循环。 So the program would not output an x
.所以程序不会输出
x
。
Any output string that doesn't contain x
is possible.任何不包含
x
输出字符串都是可能的。 In your MCQ, possibly mi
is the only option with x
and all other options contain x
somewhere in the string making them incorrect answer.在您的 MCQ 中,可能
mi
是x
的唯一选项,所有其他选项在字符串中的某处都包含x
,使它们的答案不正确。
If input is "mix....", output would be "mi".如果输入是“mix....”,输出将是“mi”。 Below is your loop unrolled.
下面是展开的循环。
getchar() -> m -> else -> print m /* First getchar */
getchar() -> i -> else -> print i /* Second getchar */
getchar() -> x -> if -> break /* Second getchar */
for(i=getchar();; i=getchar())
if(i=='x')
break;
else putchar(i);
your Code will keep on running till it encounter 'x' so whatever input you give, it will read character by character as you have used getchar() function..您的代码将继续运行,直到遇到“x”,因此无论您提供什么输入,它都会在您使用 getchar() 函数时逐个字符地读取。
like, If the input is比如,如果输入是
sparx
斯帕克斯
output will be输出将是
spar
晶石
The for loop for 循环
for(i=getchar();; i=getchar())
and syntax and structure of the for loop is for 循环的语法和结构是
for ( variable initialization; condition; variable update )
as i = getchar() will read char 'i' it is ok.因为 i = getchar() 将读取 char 'i' 没关系。 next there is no condition and final in updating you are again reading a character so it a infinite loop.
接下来没有条件,最后更新你再次读取一个字符,所以它是一个无限循环。
Loop will terminate only when it will encounter 'x'
as the statement只有当它遇到
'x'
作为语句时,循环才会终止
if(i=='x')
break;
Otherwise it will keep on printing the character.否则它将继续打印字符。
else putchar(i);
Hope it helps!!希望能帮助到你!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.