如何使用C中的struct修复无限循环

时间:2019-06-06 18:17:18

标签: c struct sentinel

在存储数据时,结构存在问题。我想做一个哨点循环,所以请看一下并帮助我,谢谢。

#include<stdio.h>
#include<stdlib.h>
struct Vehichle
{
    char vecType[100];
    char plateNo[10];
    float hours;
};
struct Parking
{
  int parkNo ;
  // 1 =true 0=false
  int availability;

};
int main()
{   
  int c = 0;
  int x;
  struct Vehichle vehicle[c];
  struct Parking park[50];


  int counter = 1; 
  while(x!=-1)
  {
    printf("Enter -1 to end: \n");
    scanf("%d", &x);
    printf("Enter Vehicle Type etc: suv,mpv and more:");
    scanf("%d",&vehicle[x].vecType);
    printf("Please enter parking Number :");
    scanf("%d",&park[x].parkNo);

    park[x].availability = 1;

    counter++;  
  }
}

我希望将其存储在结构中之后,程序将循环运行。

2 个答案:

答案 0 :(得分:2)

您的代码中存在许多问题。这是您在我的代码中添加了一些注释的代码:

int main()
{   
  int c = 0;
  int x;                      // UPS: x is uninitialized
  struct Vehichle vehicle[c]; // UPS: c is zero so you don't get an array
  struct Parking park[50];


  int counter = 1; 
  while(x!=-1)                // UPS: Use of uninitialized x
  {
    printf("Enter -1 to end: \n");
    scanf("%d", &x);
    printf("Enter Vehicle Type etc: suv,mpv and more:");
    scanf("%d",&vehicle[x].vecType);             // UPS: vecType is char array so
                                                 // use %s instead of %d
                                                 // and don't use a &
    printf("Please enter parking Number :");
    scanf("%d",&park[x].parkNo);

    park[x].availability = 1;

    counter++;

  }
}

当用户输入为-1时,您还有问题。当前代码只是继续,并在索引-1处添加了一个元素。那是非法的。

要解决此问题,请在scanf之后添加一行。喜欢:

    scanf("%d", &x);
    if (x == -1) break;  // Stop the while loop

通过此更改,您可以执行while(1)而不是while(x!=-1)

一些额外的评论:

您应检查用户输入(aka x)是否在有效范围内以用作数组索引。

您还应该检查scanf的返回值。喜欢:

if (scanf("%d", &x) != 1)
{
    // Invalid input"
    ... error handling ...
}

答案 1 :(得分:0)

(1)由于您的代码有几个问题,因此下面是更新的代码。 我敢肯定,查看下面的代码,您将能够理解代码中的错误。 随意将其用作编写自己的版本的基础。 (2)请仔细阅读内联注释。精心评论 解释该部分代码的意图 (3)这只是一个快速代码。我尚未编译/运行/测试此代码。 我的目的只是通过一个可能的示例为您提供一个想法。

/ *一个非常基本的停车管理器模块

当车辆驶入停车场时 a)捕获要停车的车辆信息和停车场编号 b)将该批次标记为不可用

当车辆离开停车场时, 捕获要清空的停车场编号, 并将该批次标记为可用

然后,在旅途中玩得开心。 * /

#include<stdio.h>
#define YOU_ARE_TRAPPED_BY_THE_BIG_BAD_GREEN_SCARY_MONSTER                                                                                                                       ({printf("HA HA HA, You didn't read and follow the inline comments !!\nNow stand up, jump 3 times, then sit down, and read all the comments again and do the min code modif to make me go away, else i won't let you escape the parking lot ... hoo ha ha ha ha >-)\n"); updateVehicleParkingInfo=1;})
#include<stdlib.h>


struct Vehichle{
    char vecType[100]; //type of vehicle eg suv,mpv and more...
    char plateNo[10];  //number plate of the vehicle
    float hours;       //???
};

struct Parking{
  int parkNo ; //parking lot num
  bool availability; //Is tbis parking space available? Yes/No
};

struct VehicleParkingInfo{
  struct Vehicle vehicle; //vehicle info
  struct Parking parking; //corresponding parking info
};

//maximum number of parking lots that the parking space has
#define MAX_PARKING_LOTS 10

//parking lot avaialble flags
#define PARKING_LOT_AVAILABLE true
#define PARKING_LOT_UNAVAILABLE false

//flags for vehicle coming in or leaving
#define VEHICLE_ENTERING true
#define VEHICLE_LEAVING false

void main(){
    int updateVehicleParkingInfo; //flag indicating that user wants to update parking info.
    int vehicleDirection; //flag for indicating whether the vehicle is coming in or going out of the parking
    int parkingIdx; //index of the parking lot to fetch values from.

    //array for info about all the parking lots
    struct VehicleParkingInfo vehicleParkingInfo[MAX_PARKING_LOTS];

    //initialize the parking & vehicle info of all the parking lots to zeros
    memset(vehicleParkingInfo,0,MAX_PARKING_LOTS*sizeof(VehicleParkingInfo));

    //for each parking lot, mark it as available and assign parking lot numbers serially
    for(parkingIdx = 0; parkingIdx < MAX_PARKING_LOTS; parkingIdx++){
        vehicleParkingInfo[parkingIdx].parking.parkNo = parkingIdx;
        vehicleParkingInfo[parkingIdx].parking.availability = PARKING_LOT_AVAILABLE;
    }

    //get user's input if parking info needs to be updated or it is time to close and go home
    printf("Update parking info? Enter 0 to end");
    scanf("%d",&updateVehicleParkingInfo);

    /*
    ****  SENTINEL LOOP  ****
    Continue updating the parking info until the user wants to even for unlimited number of times.
    Stop only when user enters a specific value i.e. 0.
    */
    while(updateVehicleParkingInfo != 0){

        printf("vehicle direction? 1 for entering, 0 for leaving:");
        scanf("%d",&vehicleDirection);

        if(vehicleDirection == VEHICLE_ENTERING){
            do{
                printf("Please enter parking Number:");
                scanf("%d",&parkingIdx);

                //*** CRASH ALERT!!! *** Following code can crash if parkingIdx is < 0, or >= MAX_PARKING_LOTS
                //TODO: (1) Add sanity check for parkingIdx (2) Add corrective steps if sanity check fails

                //if parking is not available, print an error message
                if(vehicleParkingInfo[parkingIdx].parking.availability == PARKING_LOT_UNAVAILABLE){
                    //TODO: change the below messages to fine-tune fun, humor, teasing etc levels (remember humor setting of TARS from Interstellar?)
                    printf("There is some other vehicle parked in this parking lot, please enter another parking lot number\n");
                    printf("BTW, I know which lots are available, but I won't tell you ... hehehe >-) \n, keep trying ...hoo hoo hooo\n");
                }
            //check if the requested parking lot is available, if yes, then take further actions, else request a new parking lot number
            }while(vehicleParkingInfo[parkingIdx].parking.availability == PARKING_LOT_UNAVAILABLE);

            printf("Yipee, this parking lot is available\n");

            //mark this parking lot number as being used so that another vehicle cannot come here.
            vehicleParkingInfo[parkingIdx].parking.availability = PARKING_LOT_UNAVAILABLE;

            //get vehicle type info and
            // *** CRASH ALERT!!! ***  The scanf below will crash if the user enters more 99+ characters (buffer overflow)
            // Best is to use fgets or getline with the stdin as the stream.
            // Ref https://stackoverflow.com/questions/4023895/how-do-i-read-a-string-entered-by-the-user-in-c
            // TODO: Replace below scanf() with a better/safer implmentation
            printf("Enter Vehicle Type etc: suv,mpv and more:");
            scanf("%s",vehicleParkingInfo[parkingIdx].vehicle.vecType);

            //TODO: other steps.
        }

        if(vehicleDirection == VEHICLE_LEAVING){
            do{
                printf("Please enter parking Number:");
                scanf("%d",&parkingIdx);

                //*** CRASH ALERT!!! *** Following code can crash if parkingIdx is < 0, or >= MAX_PARKING_LOTS
                //TODO: (1) Add sanity check for parkingIdx (2) Add corrective steps if sanity check fails

                //if parking is available, print an error message
                if(vehicleParkingInfo[parkingIdx].parking.availability == PARKING_LOT_AVAILABLE){
                    printf("It appears that the parking lot number is incorrect, please enter correct parking lot number\n");
                }
            //check if the requested parking lot is available, if yes, then request a new parking lot number, else proceed further
            }while(vehicleParkingInfo[parkingIdx].parking.availability == PARKING_LOT_AVAILABLE);

            printf("Bye bye, drive safely\n");

            //mark this parking lot number as available for other incoming vehicles.
            vehicleParkingInfo[parkingIdx].parking.availability = PARKING_LOT_AVAILABLE;
        }

        //get user's input if parking info needs to be updated or it is time to close and go home
        printf("Update parking info? Enter 0 to end");
        scanf("%d",&updateVehicleParkingInfo);

        //TODO: remove the following line of code before running the program
        YOU_ARE_TRAPPED_BY_THE_BIG_BAD_GREEN_SCARY_MONSTER;

        //go back to while loop,
        //check if the vehicle parking info needs to be updated,
        //break if the user has entered 0

    }//end of the Sentinel loop

    //the above loop will run indefinitely. The user has quite a lot of ways to come out of the loop
    //(1) Enter the sentinel value '0', (easiest path)
    //(2) Somehow stop the program e.g. by banging his/her head really hard on the computer such that computer breaks .. etc


}//end of main()