简体   繁体   中英

Why doesn't this loop want to work properly?

I've been at this for hours but I want to be able to add another diver and the only thing I need to show for it is the number of divers that were judged and their average score which I can do once this issue is fixed.

It runs but when it loops around, it skips city, and eventually crashes the 2nd to 3rd time around. Can anyone help?

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main(){
    string name;
    string city;
    double judge[4];

    double total = 0;
    double score;
    int divers = 1;
    int x = 0;
    int y = 1;

    do{
        cout << "Please enter divers name: ";
        getline(cin, name);
        cout << "Enter the diver's city: ";
        getline(cin, city);

        do{
            cout << "Enter the score given by judge #" << y << ": " ;
            cin >> judge[x];

            total = total + judge[x];

            y++;
            x++;
        } while(y < 6);

        y = 1;

        cout << "Divers?";
        cin >> divers;

    } while(divers == 1);

    cout << city << endl;
    cout << name << endl;
    cout << total << endl;
    cout << judge[0] << endl;
    cout << judge[1] << endl;
    cout << judge[2] << endl;
    cout << judge[3] << endl;
    cout << judge[4] << endl;

    system("PAUSE");
}

索引从 0 开始,声明judge[4]意味着您将judge索引设为 0 1 2 3。您正在访问数组的末尾。

When you do cin >> divers; the end-of-line character is not removed from the input, just the number leading up to it. Then, the next time you ask for a line with std::getline() it returns just the end-of-line character that is already there and does not wait for your new input.

So when you do cin >> drivers style input before a std::getline() style input you need to read past the end-of-line character.

One way to do that is using the ignore() function:

do{
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

    cout << "Please enter divers name: ";
    getline(cin, name);
    cout << "Enter the diver's city: ";
    getline(cin, city);

    // ...

Another way is to use the white-space eater std::ws in your std::getline() calls:

do{
    cout << "Please enter divers name: ";
    getline(cin >> std::ws, name);
    cout << "Enter the diver's city: ";
    getline(cin >> std::ws, city);

    // ...

Strictly speaking only the first one is necessary. Remember the white-space eater will eat all the initial spaces you type into the getline() so you can't read in leading spaces if you use that technique.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM