0

我最近开始用 c 编码,在编码过程中遇到了这个运行时错误,我找不到解决方案。它要么显示此运行时错误,要么scanf在找到客户的情况下停止,您选择要编辑的内容,然后输入新信息。

例子:

  • 输入 ID:322993
  • 成立
  • 按 [1] 编辑 ID
  • 输入新身份证
  • 程序卡住了

这是代码:

void modifyCustomer(){
    int counter=0;
    long int tempID=0;
    flag found = false;
    fflush(stdin);
    printf("Enter Customer ID\n");
    scanf("%lld", &tempID);
    do{
        char option_str[200];
        int option = 0;
        char *not_valid;
        if(tempID == customers[counter].customerID){
            printf("Customer found!\n");
            found = true;
            do{
                fflush(stdin);
                printf("Choose what to modify:\n 1. ID\n 2. Name\n 3. Surname\n 4. Address\n 5. Mobile\nOption: ");
                scanf("%s", &option_str);
                option = strtol(option_str, &not_valid, 10);
                fflush(stdin);
                if (*not_valid != '\0') {
                    printf("%s is not valid.\n", not_valid);
                } else{
                    switch(option){
                    case 1:
                        printf("Enter new ID:\n");
                        scanf("%d\n", &customers[counter].customerID);
                        printf("Customer Modified Successfully!\n");
                        break;
                    case 2:
                        printf("Enter new Name:\n");
                        scanf("%s\n", &customers[counter].customerName);
                        printf("Customer Modified Successfully!\n");
                        break;
                    case 3:
                        printf("Enter new Surname:\n");
                        scanf("%s\n", &customers[counter].customerSurname);
                        printf("Customer Modified Successfully!\n");
                        break;
                    case 4:
                        printf("Enter new Address:\n");
                        scanf("%s\n", &customers[counter].customerAddress);
                        printf("Customer Modified Successfully!\n");
                        break;
                    case 5:
                        printf("Enter new Mobile:\n");
                        scanf("%lld\n", &customers[counter].customerMobile);
                        printf("Customer Modified Successfully!\n");
                        break;
                    default:
                        printf("You did not enter a valid Number. Please re-enter your Input \n");
                        break;
                    }
                }
            }while((option <1) || (option > 5));
        }
        else{
            counter++;
        }
    }while((found != true) && (counter < (custNum-1)));
    if (found == false)
        printf("Customer not found!\n");
}

为什么会这样?

4

1 回答 1

1

格式说明%lld符用于long long. 您已经声明了一个long int所以可能正在尝试写入比您的存储空间更大的类型。sizeof(long int) != sizeof(long long)这样做的影响是未定义的,但如果在您的平台上,很可能会覆盖下一个堆栈变量。

您可以通过更改tempID为 typelong int或将您使用的格式说明符更改为%ld.

于 2012-12-10T17:19:20.280 回答