我正在编写一些代码,在将文本进一步发送到程序之前对其进行过滤(该代码删除了除所有字母数字字符和下划线之外的所有内容),代码本身工作得很好,除了我无法找到一种方法存储它的输出以供程序的其他部分使用,如果我不得不猜测,这可能涉及将 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/