问题描述
这是我在K& R2练习1-10的尝试。代码看起来很邋$
我。有更优雅的方法吗?
#include< stdio.h>
/ *将输入复制到输出,打印* /
/ *系列空白为单一* /
int main(){
int c;
while((c = getchar())!= EOF){
putchar(c);
if(c ==''' '){
while((c = getchar())=='''')
; / * null声明* /
putchar(c);
}
}
返回0;
}
在
Gentoo框中使用gcc-3.4.6编译时,它会产生预期的输出。所以我假设代码至少是正确的,但不是
必然是最优的。
JZ
This is my attempt at exercise 1-10 in K&R2. The code looks sloppy to
me. Is there a more elegant way to do this?
#include <stdio.h>
/* copies input to output, printing */
/* series of blanks as a single one */
int main() {
int c;
while ((c = getchar()) != EOF) {
putchar(c);
if (c == '' '') {
while ((c = getchar()) == '' '')
; /* null statement */
putchar(c);
}
}
return 0;
}
It produces the expected output when compiled with gcc-3.4.6 on a
Gentoo box. So I''m assuming the code is at least correct, though not
necessarily optimal.
JZ
推荐答案
这不打印额外的空间吗?你在if之前打印了这个角色。
-
Ian Collins。
Doesn''t this print an extra space? You printed the character before the if.
--
Ian Collins.
哎呀,我的意思是练习1-9。在我发布这个之后我也意识到
那里可能有大量的代码用于这个精确的练习。我会
搜索群组档案。
Oops, I meant exercise 1-9. I also realized after I posted this that
there''s probably a ton of code out there for this exact exercise. I''ll
search the group archives.
这不打印额外的空间吗?你在if之前打印了这个角色。
Doesn''t this print an extra space? You printed the character before the if.
我在几个不同的输入上测试了它,它似乎产生了
所需的输出。例如,输入argle bargle和argle bargle。产生输出
" argle bargle" ;.
JZ
I tested it on several different inputs, and it seems to produce the
desired output. For example, input "argle bargle" produces output
"argle bargle".
JZ
哎呀,我的意思是练习1-9。在我发布这个之后我也意识到
那里可能有大量的代码用于这个精确的练习。我会
搜索群组档案。
Oops, I meant exercise 1-9. I also realized after I posted this that
there''s probably a ton of code out there for this exact exercise. I''ll
search the group archives.
这不打印额外的空间吗?你在if之前打印了这个角色。
Doesn''t this print an extra space? You printed the character before the if.
我在几个不同的输入上测试了它,它似乎产生了
所需的输出。例如,输入argle bargle和argle bargle。产生输出
" argle bargle" ;.
I tested it on several different inputs, and it seems to produce the
desired output. For example, input "argle bargle" produces output
"argle bargle".
傻傻的我,我没有发现在终止时用c!='' ''。
-
Ian Collins。
Silly me, I didn''t spot the while terminating with c != '' ''.
--
Ian Collins.
这篇关于在K& R2中练习1-10的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!