gpt4 book ai didi

c - 使用 scanf() 将标识符读入 C 程序

转载 作者:太空宇宙 更新时间:2023-11-04 06:07:01 24 4
gpt4 key购买 nike

我需要我的 C 程序能够使用 C 中的 scanf() 方法读取标识符。

在这种情况下,标识符是一个字母或一个 _ 字符,后跟一个或多个字母数字字符,包括 _ 字符。

正则表达式是

    [a-ZA-Z_][a-zA-Z0-9_]*

这些是正确标识符的示例:

    _identifier1
variable21

这些是不正确标识符的例子

    12var
%foobar

有人知道如何在 C 中使用 scanf() 来完成吗?

最佳答案

scanf() 不支持正则表达式。标准 C 库中根本不支持正则表达式。您必须读取一个字符串,然后“手动”解析它。

例如:

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

int isIdentifier(const char* s)
{
const char* p = s;

if (!(*p == '_' || isalpha(*p)))
{
return 0;
}

for (p++; *p != '\0'; p++)
{
if (!(*p == '_' || isalnum(*p)))
{
return 0;
}
}

return 1;
}

int main(void)
{
const char* const testData[] =
{
"a",
"a_",
"_a",
"3",
"3a",
"3_",
"_3"
};
int i;

for (i = 0; i < sizeof(testData) / sizeof(testData[0]); i++)
{
printf("\"%s\" is %san identifier\n",
testData[i],
isIdentifier(testData[i]) ? "" : "not ");
}

return 0;
}

输出:

"a" is an identifier
"a_" is an identifier
"_a" is an identifier
"3" is not an identifier
"3a" is not an identifier
"3_" is not an identifier
"_3" is an identifier

关于c - 使用 scanf() 将标识符读入 C 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8368681/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com