具体问题是:用户输入文本,例如,如果用户输入
hello (spaces) (spaces) world用户获得的输出是
hello (space) world.下面是我的代码,可以实现空格数的调整,我有点困惑,因为我的输出会吃掉第一个字母。我想知道为什么会这样。
代码:
#include <stdio.h>
int main() {
int characters = 0;
while ((characters = getchar()) != EOF) {
if (characters != ' ') {
putchar(characters);
}
if (characters == ' ') {
while ((characters = getchar()) == ' ');
putchar(' ');
}
}
}输出:
Hello world world world
Hello orld orld orld

发布于 2018-12-19 04:01:08
if (characters == ' '){
while ((characters = getchar()) == ' ');
putchar(' ');
}这段代码将继续使用字符,直到它吃掉一个非空间。但你不想吃任何非空间的东西。一个简单的解决办法:
if (characters == ' '){
while ((characters = getchar()) == ' ');
putchar(' ');
putchar(characters);
}现在你吃字符直到你吃了一个非空间,然后你输出一个空格,然后你输出你吃的非空间字符。
https://stackoverflow.com/questions/53844384
复制相似问题