我正在研究一些代码,在将文本进一步发送到程序之前过滤文本(此代码删除除了所有字母数字字符和下划线之外的所有内容),代码本身工作正常,除了我无法找到存储输出的方法如果我不得不猜测,这可能涉及将stdout从putchar保存到变量中,但是如果有人能指出我正确的方向,那么我无法在网上找到这么多信息.为此,我真的很感激,谢谢!
#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;
}
Run Code Online (Sandbox Code Playgroud)
也许我不理解你putchar()在进行过滤时"需要"使用,但你可以将输入过滤到输出中array of chars,以便在过滤后使用,如下所示.
#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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
hel123_lo
[hel123_lo]
Run Code Online (Sandbox Code Playgroud)
编辑:
如果你想只是将字符串过滤成数组而不显示字符串,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;
}
Run Code Online (Sandbox Code Playgroud)
你究竟想要对过滤后的文本输出做些什么?