我怎样才能实现指令
printf(" ");
被触发然后循环结束?我必须为我的类(class)编写一个程序,用一个空格替换所有制表符和空格。
#include <stdio.h>
int main()
{
int a;
while (a != EOF)
{
a=getchar();
while (a==" " || a=="\t")
a=EOF;
/*I want to put printf(" "); here */
putchar(a);
}
return 0;
}
最佳答案
您的程序因多种原因不正确:
a
在您第一次将它与EOF
进行比较时被初始化,因此行为未定义。- 您无法有意义地将字符
a
与字符串""
进行比较。将a
与带单引号的字符常量进行比较:a == ' '
。 - 当您检测到空格或制表符时,您不会阅读更多字符
- 您只想在出现一系列空白时打印空格。
这是一种不同的方法:一次读取一个字符,如果它是一个空格,则设置一个空格指示符,如果不是输出前面有一个空格的字符,如果设置了指示符并重置指示符。
这是一个例子:
#include <stdio.h>
int main() {
int c;
int insert_space = 0;
while ((c = getchar()) != EOF) {
if (c == ' ' || c == '\t') {
insert_space = 1;
} else {
if (insert_space) {
putchar(' ');
insert_space = 0;
}
putchar(c);
}
}
if (insert_space) {
/* there are spaces and/or tabs at the end of the last line
* of the file, which is not newline terminated. It might be
* a good idea to remove these completely.
*/
putchar(' ');
}
return 0;
}
当以自己的源代码作为输入运行时,输出为:
#include <stdio.h>
int main() {
int c;
int insert_space = 0;
while ((c = getchar()) != EOF) {
if (c == ' ' || c == '\t') {
insert_space = 1;
} else {
if (insert_space) {
putchar(' ');
insert_space = 0;
}
putchar(c);
}
}
if (insert_space) {
/* there are spaces and/or tabs at the end of the last line
* of the file, which is not newline terminated. It might be
* a good idea to remove these completely.
*/
putchar(' ');
}
return 0;
}
关于c - C中循环结束时如何执行指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52633001/