问题是在输入结构变量期间,在某些输入之后,它不会打印输入语句,而是将输入随机分配给变量

时间:2018-09-04 17:40:34

标签: c arrays input structure

#include <stdio.h>
#include<stdlib.h>

struct complex {
  int real;
  int img;
} s1[2], s2;

int main() {
  int n;
  printf("\t******MAIN MENU*******\n");
  printf(
      "1-Read Complex number\n2-Display Complex number\n3-Add\n4-Subtract\n5-EXIT\n");

  while (1) {
    printf("Enter your choice \n");
    scanf("%d", &n);
    switch (n) {
      case 1:
        for (int i = 0; i < 2; i++) {
          printf("Enter real and imaginary parts of complex number %d \n",
              i + 1);
          scanf("%d ", &s1[i].real);
          scanf("%d ", &s1[i].img);
        }
        break;
      case 2:
        for (int j = 0; j < 2; j++) {
          printf("Complex number %d = ", j + 1);
          printf("%d + %di\n", s1[j].real, s1[j].img);
        }
        break;
      case 3:
        printf("The sum of two Complex Numbers Are = ");
        s2.real = s1[0].real + s1[1].real;
        s2.img = s1[0].img + s1[1].img;
        printf("%d + %di\n", s2.real, s2.img);
        break;
      case 4:
        printf("The difference of two Complex Numbers Are = ");
        s2.real = s1[0].real - s1[1].real;
        s2.img = s1[0].img - s1[1].img;
        printf("%d + %di", s2.real, s2.img);
        break;
      case 5:
        exit(0);
      default:
        printf("\n Wrong choice \n");
    }
  }
  return 0;
}

1 个答案:

答案 0 :(得分:1)

阅读复数部分时:

      scanf("%d ", &s1[i].real);
      scanf("%d ", &s1[i].img);

%d格式说明符需要一个数字序列。问题是它消耗了任意数量的空白字符后的空格。键入数字并按ENTER键后,scanf不会返回,直到输入了一些非空格字符,即您要键入的下一个数字。

去除格式字符串中的尾随空格:

      scanf("%d", &s1[i].real);
      scanf("%d", &s1[i].img);