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

Won't let me enter information next time through the while (true) loop

本文关键字:true 循环 信息 输入 while 下次      更新时间:2023-10-16

第一次迭代将正常工作。我可以输入歌曲标题、艺术家和评级。但是,下次它将显示"输入歌曲标题"和"输入艺术家:",这意味着我下次无法输入歌曲标题。我确定这是一个简单的错误,但我找不到它。这是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; 
    }
}

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

std::cout << "Enter song title - XYZ to quit: ";
std::cin.ignore();                                                             /*
^^^^^^^^^^^^^^^^^^                                                             */
std::cin.getline(song, 256);