我一直在研究一些关于 C 的书籍,试图让我的 C 腿(海腿!明白了吗?!)。我刚刚完成了 K&R 书中的练习 1-9,作为引用,它是“编写一个程序将其输入复制到输出,用一个空格替换一个或多个空格的每个字符串”。不过,我对我的代码发生了什么有疑问——
#include <stdio.h>
//Copy input to output. Replace each string of multiple spaces with one single space
int main(int argc, char *argv[]){
int ch, lch; // Variables to hold the current and last characters, respectively
/* This loop should 'put' the current char, then store the current char in lc,
* loop back, 'get' a new char and check if current and previous chars are both spaces.
* If both are spaces, do nothing. Otherwise, 'put' the current char
*/
for(ch = getchar(); (ch = getchar()) != EOF; lch = ch){
if(ch == ' ' && lch == ' ')
;
else putchar(ch);
}
return 0;
}
除了第一个字符输入外,这大部分都有效。例如,如果第一行输入是
"This is a test"
我的代码输出
"his is a test".
在放弃第一个字符输入后,程序会始终如一地工作以满足练习的要求。
有人可以告诉我我在循环中犯的错误导致了这个问题吗?也欢迎任何其他建议。
最佳答案
在 for 循环语句中,您遇到了错误。
for(ch = getchar(); (ch = getchar()) != EOF; lch = ch){...}
在这里,您将第一个字符存储在 ch 中,然后通过再次读取字符输入再次测试 if (ch!=EOF)。
从初始化语句中删除ch=getchar()
;让它在第二部分。
for(;(ch = getchar()) != EOF; lch = ch){...}
此外,您必须在运行 lch 之前对其进行初始化,因为在循环的第一次迭代中进行比较之前,lch 中不会存储任何值。所以,让lch=0
先被初始化。
for(lch = 0; (ch = getchar()) != EOF; lch = ch){...}
考虑在您的编译器中启用警告,它可能会检测并警告此问题,因此您可以修复它。
以上内容可以解决您的问题。
(感谢蓝月亮和hyde帮我修改答案。)
关于c - K&R Exercise 1-9 : output the input, 用一个空格替换多个空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31597961/