不会让我通过while(true)循环下次输入信息

时间:2013-11-12 00:50:36

标签: c++ while-loop

第一次迭代将完美地运行。我可以输入歌曲标题,艺术家和评级。但是,下一次,它将显示“输入歌曲标题”和“输入艺术家:”,这意味着我下次不能输入歌曲标题。我确定这是一个简单的错误,但我找不到它。这是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; 
    }
}

1 个答案:

答案 0 :(得分:3)

您需要丢弃上次输入操作中保留在流中的新行。请使用std::cin.ignore()

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

std::cin.ignore();                                                             /*
^^^^^^^^^^^^^^^^^^                                                             */
std::cin.getline(song, 256);