2

第一次迭代将完美无缺。我可以输入歌曲名称、艺术家和评分。但是,下一次,它会显示“输入歌曲名称”和“输入艺术家:”,这意味着我下次无法输入歌曲名称。我确定这是一个简单的错误,但我找不到它。这是 C++。

#include <iostream>

using namespace std;

void printResults(double ratingOfSong);

int main(void)
{
    bool getInput = true;
    char song[256];
    char artist[256];

    cout << "Thank you for taking the time to rate different songs." << endl
         << "This will better improve our quality to better serve you." << endl
         << "Please enter song title, artist, and a rating out of 5 stars." << endl << endl << endl;

    while ( getInput ) 
    {
        cout << "Enter song title - XYZ to quit: ";
        cin.getline(song,256);
        if ( song[0] == 'X' && song[1] == 'Y' && song[2] == 'Z') 
        {
            getInput = false;
            cout << "Thank you for taking the time in rating the songs." << endl;
            break;
        }
        else
        {
            double rating = 0;
            cout << "Enter artist: ";
            cin.getline(artist,256);
            cout << "Enter rating of song: ";
            cin >> rating;
            printResults(rating);
        }
    }

}

void printResults(double ratingOfSong)
{
    if (ratingOfSong <= 1.5)
    {
        cout << "We are sorry you didn't like the song. Thanks for the input." << endl << endl;
    }
    else if (ratingOfSong > 1.5 && ratingOfSong <= 3.0)
    {
        cout << "We hope the next song you buy is better. Thanks for the input." << endl << endl;
    }
    else if (ratingOfSong > 3.0 && ratingOfSong <= 4.0)
    {
        cout << "We are glad that you somewhat enjoy the song. Thanks for the input." << endl << endl;
    }
    else if (ratingOfSong > 4.0 && ratingOfSong < 5.0)
    {
        cout << "We are glad that you like the song! Thanks for the input." << endl << endl;
    }
    else if (ratingOfSong >= 5.0)
    {
        cout << "A perfect score, awesome! Thanks for the input." << endl << endl; 
    }
}
4

1 回答 1

3

You need to discard the new line that was left in the stream from the last input operation. Use std::cin.ignore() for that:

std::cout << "Enter song title - XYZ to quit: ";

std::cin.ignore();                                                             /*
^^^^^^^^^^^^^^^^^^                                                             */
std::cin.getline(song, 256);
于 2013-11-12T01:03:10.177 回答