构造函数不在c ++ switch语句中显示值

时间:2017-04-14 15:06:09

标签: c++ constructor switch-statement

您好我正在尝试为此渡轮建立一个程序以跟踪可用空间,但我仍然试图输出用户在构造函数中给出的值。所以问题出现在案例5中我试图输出它。 for循环不起作用因为它会破坏它但是一个while循环也没有用。创建一个单独的功能也没有用。帮助将非常感激。

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

struct cars {
    int carlength, carcount;
    string registrationnumber;
    int carseats;
} caaars[100];

void printcars(cars car);  

int n, x;

int main()
{
    int loop = 0;
    string mystr, mystr1, mystr2;
    int ferrylength;
    cout << "The Ferry Program\n\n";

    cout << "Please enter the length of the ferry in meters: ";
    cin >> ferrylength;

    while (loop == 0) {
        system("cls");
        cout << "Choose a vehicle \n\n";
        cout << "1: Car.\n";
        cout << "2: Bus.\n";
        cout << "3: Lorrie.\n";
        cout << "4: Digger.\n";
        cout << "5: To print a report.\n";
        cout << "6: To close the program.\n\n";
        int choice;
        cin >> choice;
        switch (choice) {

        case 1:{
            cout << "\nEnter the amount of cars needed to be placed on the ferry: ";
            cin >> x;
            cin.ignore();
            while (n != x)
            {

                cout << "\nPlease enter the length of the car in metres: ";
                getline(cin, mystr);
                stringstream(mystr) >> caaars[n].carlength; //for integers.

                cout << "\nPlease enter the Registration number: ";
                getline(cin, caaars[n].registrationnumber); //For strings and both

                cout << "\nPlease enter the amount of seats in the car: ";
                getline(cin, mystr2);
                stringstream(mystr2) >> caaars[n].carseats;



                n++;
            }
        }

            break;
        case 2:


            break;
        case 3:

            break;

        case 4: 

            break;

        case 5: 
        {
            int l;
             l = 0;
            for (l = 0; l < x; l++) 

                printcars(caaars[n]);
        }

            break;

        case 6: 
            loop++;
            break;
        }// end of while loop. 
    }
    return 0;
}

void printcars(cars car) {
    int p = 1;

    system("cls");
    cout << "Car ";
    cout << p; cout << ":" << endl;
    cout << "\nThe registration number is: ";
    cout << car.registrationnumber << endl; 
    cout << "\nThe car length is: ";
    cout << car.carlength << endl;
    cout << "\nAmount of car seats: ";
    cout << car.carseats << endl;


    p++;
}

1 个答案:

答案 0 :(得分:1)

您正在使用n进行迭代,而您应该使用l代替:

case 5: 
{
    int l;
        l = 0;
    for (l = 0; l < x; l++) 

        printcars(caaars[l]);
}