使用scanf()将标识符读入C程序 [英] Reading an Identifier into a C Program using scanf()
问题描述
我需要我的C程序能够使用C中的scanf()方法读取标识符.
I need my C program to be able to read in an identifier using the scanf() method in C.
在这种情况下,标识符是字母或_字符,后跟一个或多个字母数字字符,包括_字符.
An identifier in this case is a letter or a _ character followed by one or more alphanumeric characters including the _ character.
正则表达式为
[a-ZA-Z_][a-zA-Z0-9_]*
这些是正确标识符的示例:
These are examples of correct identifiers:
_identifier1
variable21
这些是标识符不正确的示例
These are examples of incorrect identifiers
12var
%foobar
有人知道如何在C语言中使用scanf()完成此操作吗?
Does anybody know how this would be done using scanf() in C?
推荐答案
scanf()
不支持正则表达式.标准C库完全不提供正则表达式支持.您必须先读取一个字符串,然后手动"解析它.
scanf()
doesn't support regular expressions. There's no regular expression support at all in the standard C library. You'll have to read a string and then parse it "manually".
例如:
#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
这篇关于使用scanf()将标识符读入C程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!