c - C中循环结束时如何执行指令

标签 c loops for-loop while-loop

我怎样才能实现指令

 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/

相关文章:

c - IPC System V 消息队列 - 发送一个数组 block

c++ - * 三角形图案设计问题

python-3.x - 使用 for 循环遍历字节对象 python 3x

for-loop - 打破 tcl 中的父循环

javascript - 迭代大型数据集的 Excel VBA 与 Javascript 性能对比

c - 如何在for循环中执行()?在 C

c - 将变量分配给数组位置 [C]

c - 我的程序在尝试从链接列表中删除元素时抛出异常

java - 如何打印下面的图案

python - 使用基本库优化python代码