假设我从用户那里得到q3等输入。我需要将其作为输入并将q分别存储为字母,将3存储为数字。请告诉我如何使用代码在c中执行此操作?
答案 0 :(得分:0)
#include <stdio.h>
#include <stdlib.h>
int main() {
char line[BUFSIZ];
char c;
int n;
printf("Enter: ");
fgets(line, sizeof line, stdin); // read a line of input
c = line[0]; // put first letter from line into c
n = atoi(line + 1); // interpret second letter onwards as an integer
printf("Letter: %c\n", c);
printf("Number: %d\n", n);
return 0;
}
答案 1 :(得分:0)
#include <stdio.h>
int main(int argc, char *argv[])
{
const char str[] = "q3";
char ch;
int num;
sscanf(str,"%c%d",&ch,&num);
printf("char: '%c' num: '%d'\n", ch, num);
return 0;
}
N.B。观察sscanf()中的&符号(&amp;)。忘记放入这些是一个非常常见的编码错误。