c - 如何将 putchar 的输出保存到变量中

标签 c

我正在编写一些代码,在将文本进一步发送到程序之前对其进行过滤(该代码删除了除所有字母数字字符和下划线之外的所有内容),代码本身工作得很好,除了我无法找到一种方法存储它的输出以供程序的其他部分使用,如果我不得不猜测,这可能涉及将 putchar 中的 stdout 保存到变量中,但如果有人可以指出我,我在网上找不到太多这样做的信息正确的方向,我真的很感激,谢谢!

#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void) {
    int i;
    char *p;
    char stg[] = "hello";
        for (p = &stg[0]; *p != '\0'; p++) {
           if (isalnum(*p) || *p == '_') {
           putchar (*p);
           }
        }
        putchar ('\n');
    return 0;
}

最佳答案

也许我不明白您在进行过滤时“需要”使用putchar(),但您可以将输入过滤到输出字符数组中过滤后根据需要使用,如下所示。

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(void) {
    int i;
    char *p;
    char stg[] = "hel123*^_lo";
    char output[200] = {0x00};
    int index = 0;


    p = stg;
    while( *p )
    {
        if (isalnum(*p) || *p == '_')
        {
            output[index++] = (char)putchar(*p);
        }       
        p++;
    }
    putchar('\n');
    printf("[%s]\n", output);
    return 0;
}

输出:

hel123_lo
[hel123_lo]

编辑:

如果您只想将字符串过滤到数组中而不使用 putchar() 显示字符串,您可以执行以下操作:

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(void) {
    int i;
    char *p;
    char stg[] = "hel123*^_lo";
    char output[200] = {0x00};
    int index = 0;


    p = stg;
    while( *p )
    {
        if (isalnum(*p) || *p == '_')
        {
            output[index++] = *p;
        }       
        p++;
    }

    printf("[%s]\n", output);
    return 0;
}

您到底想对过滤后的文本的输出做什么?

关于c - 如何将 putchar 的输出保存到变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10559661/

相关文章:

java - 从 Java 与 C 可执行文件通信

c - 在线程创建时将一个简单整数传递给线程的启动函数

c - 程序不读取整个文件

c - 包含不同目录中文件的 Makefile

c - 查找以特定字符开头并在 C 中显示的所有可能单词(使用二叉树的字典实现)

c - 从文件 C 中的单行读取多个变量类型

c - 如何释放内部有结构单元格的链表?

c++ - 如何从预定义数组创建特定元素数组

c - 为什么在查找倾斜内存地址的行时需要 char* 强制转换?

c - C 中结构的逻辑运算符