我在 C 编程课中有一项作业,要求仅使用函数 getchar
和 putchar
输出一首诗,每个单词都在新行上。我已经编写了程序的大部分内容,但我不知道如何只为多个空格添加一个新行。例如,当有多个空格时,输出中就会出现间隙,这是我不想要的。有谁知道如何纠正这个问题吗?
int main(int argc, const char * argv[])
{
/* Variables declared */
int iochar;
/* While loop */
while ((iochar = getchar() ) != EOF) {
/* If statement to return on alphabetic characters, not puncuation */
if (((iochar >= 'A') && (iochar <= 'Z')) || ((iochar >= 'a') && (iochar <= 'z'))) {
putchar(iochar);
}
/* If statement to produce a new line when a space is detected */
if (iochar == ' ') {
putchar('\n');
}
}
return 0;
}
最佳答案
您可以将前一个字符存储在另一个变量中,并且仅当当前字符是空格且前一个字符不是空格时才输出换行符。
顺便问一下:输入中的数字会发生什么?
关于c - 用 C 输出一首诗,每个单词换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12486421/