我正在尝试读取以下格式的输入 [AZ],123 并存储结果。例如 'A,123' 或 'B, 456'(单个大写字母,后跟冒号,后跟整数,允许空格)
我通过多次单独调用 scanf 来实现这一点。但我正在尝试使用对 scanf 的一次调用来完成此操作。
我不明白为什么以下不起作用:
char temp[23];
int a = 0;
int result = scanf("%1[A-Z]s , %d", temp, &a);
printf("%d = %d, %s\n", result, a, temp);
Run Code Online (Sandbox Code Playgroud)
此代码返回 1 并且变量 a 从未设置。我正在编译使用gcc -ansi -pedantic
int result = scanf("%1[A-Z]s , %d", temp, &a);
// ^^^
// read 1 letter, a literal "s", optional whitespace,
// a literal comma, optional whitespace, an integer
Run Code Online (Sandbox Code Playgroud)
与
int result = scanf("%1[A-Z] , %d", temp, &a);
// no s
// read 1 letter, optional whitespace,
// a literal comma, optional whitespace, an integer
Run Code Online (Sandbox Code Playgroud)
为了告诉天气,解析失败,因为没有逗号或者因为第二个参数不是数字,将逗号读入变量,然后检查它:
char ch;
int result = scanf("%1[A-Z] %c%d", temp, &ch, &a);
if (result == 3 && ch == ',') /* all ok */;
if (result == 2) /* a not read */;
Run Code Online (Sandbox Code Playgroud)
我似乎无法在此计算机上添加评论。