要从字符串ai+b中提取a,即使a的值和'i'之间有一个空格,只需使用sscanf并检查它是否返回 1 以验证您是否阅读了 int
最后还要提取运算符和 b 就可以了
sscanf(argv[1], "%d i %c %d", &a, &oper, &b)
并检查它返回 3 个 oper 是否有效,例如:
#include <stdio.h>
int main(int argc, char ** argv)
{
int a, b;
char oper;
if (argc != 2)
printf("Usage: %s <ai+b>\n", *argv);
else if ((sscanf(argv[1], "%d i %c %d", &a, &oper, &b) == 3)
&& ((oper == '+') || (oper == '-')))
printf("a=%d b=%d oper=%c\n", a, b, oper);
else
puts("invalid input");
return 0;
}
编译和执行:
pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out ai+2
invalid input
pi@raspberrypi:/tmp $ ./a.out 12i+3
a=12 b=3 oper=+
pi@raspberrypi:/tmp $ ./a.out "12i + 3"
a=12 b=3 oper=+
pi@raspberrypi:/tmp $ ./a.out "12 i + 3"
a=12 b=3 oper=+
pi@raspberrypi:/tmp $ ./a.out "12 i - 3"
a=12 b=3 oper=-
pi@raspberrypi:/tmp $ ./a.out "12i+-3"
a=12 b=-3 oper=+
pi@raspberrypi:/tmp $ ./a.out "-12i+-3"
a=-12 b=-3 oper=+
pi@raspberrypi:/tmp $ ./a.out "-12i*-3"
invalid input
pi@raspberrypi:/tmp $
注意我允许直接输入1i-2 而不是强制输入1i+-2 不太实用,因为我允许运算符为'-',如果您不想允许这种简化形式:
#include <stdio.h>
int main(int argc, char ** argv)
{
int a, b;
if (argc != 2)
printf("Usage: %s <ai+b>\n", *argv);
else if (sscanf(argv[1], "%d i + %d", &a, &b) == 2)
printf("a=%d b=%d\n", a, b);
else
puts("invalid input");
return 0;
}
编译和执行:
pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out ai+2
invalid input
pi@raspberrypi:/tmp $ ./a.out 12i+3
a=12 b=3 oper=+
pi@raspberrypi:/tmp $ ./a.out "12i + 3"
a=12 b=3 oper=+
pi@raspberrypi:/tmp $ ./a.out "12 i + 3"
a=12 b=3 oper=+
pi@raspberrypi:/tmp $ ./a.out "12 i - 3"
invalid input
pi@raspberrypi:/tmp $ ./a.out "12i+-3"
a=12 b=-3 oper=+
pi@raspberrypi:/tmp $ ./a.out "-12i+-3"
a=-12 b=-3 oper=+
pi@raspberrypi:/tmp $ ./a.out "-12i*-3"
invalid input
pi@raspberrypi:/tmp $ ./a.out "-12i++3"
a=-12 b=3 oper=+
pi@raspberrypi:/tmp $
关于您的更新,您的 sscanf 输入字符串无效,因为您提供了 NULL 指针,您想要这样的东西:
#include <stdio.h>
int main()
{
char line[64];
int a;
int b;
int c;
int d;
int finala;
int finalb;
printf("Enter the first complex number in the form ai + b: ");
if ((fgets(line, sizeof(line), stdin) == NULL) ||
(sscanf(line, "%d i + %d", &a, &b) != 2)) {
puts("invalid form");
return -1;
}
printf("Enter the second complex number in the form ai + b: ");
if ((fgets(line, sizeof(line), stdin) == NULL) ||
(sscanf(line, "%d i + %d", &c, &d) != 2)) {
puts("invalid form");
return -1;
}
finala = b*c + a*d;
finalb = b*d + a*c*(-1);
printf("(%di + %d) * (%di + %d) = %di + %d\n", a, b, c, d, finala, finalb);
}
编译和执行:
pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out
Enter the first complex number in the form ai + b: 1i+2
Enter the second complex number in the form ai + b: -2i+6
(1i + 2) * (-2i + 6) = 2i + 14
pi@raspberrypi:/tmp $