所以我正在做 Ritchie/Kernighan 编写的 C 编程语言第 2 版中的练习。专门练习1.9。 “编写一个程序将它的输入复制到输出,用一个空格替换每个字符串。”
我相信我的解决方案是正确的,但每次我点击进入屏幕时都会输出我的行而不是等待 EOF。这是预期的行为吗?我只使用他在书中复习过的函数和关键字。
如果我有多个换行符,我如何强制它等到我输入 eof 才能得到输出? Putchar 一次只处理一个字符,所以也许这是不可能的。
还有什么是退格键?他指的是空格键的空格吗?
/*
Copys its input to its output, replacing each string with multiple blanks with one.
Input - "I am running."
Output - "I am running."
*/
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
for (int c = getchar(); c != EOF; ){
while (c == ' '){
c = getchar();
if (c != ' '){
putchar(' ');
}
}
putchar(c);
c = getchar();
}
return 0;
}
改进版本:
int _tmain(int argc, _TCHAR* argv[])
{
int c;
while ((c = getchar()) != EOF){
while (c == ' '){
c = getchar();
if (c == EOF){
break;
}
if (c != ' '){
putchar(' ');
}
}
putchar(c);
}
return 0;
}
最佳答案
看看theory-behind-getchar-and-putchar-functions它解释了为什么你在每一行之后得到输出。
要强制程序在输出前等待 EOF,您需要使用某种缓冲区,请查看 print-multiple-lines-by-getchar-and-putchar
关于c - 每次我按回车键时 Putchar 和 Getchar 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29284431/