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

标签 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; 
    }
}

最佳答案

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

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

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

关于c++ - 下次不会让我通过 while (true) 循环输入信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19918933/

相关文章:

c++ - while循环困惑

python - 只要没有错误,如何运行while循环

c - 使用 getchar() 和 putchar() 评估字符序列

android - ANeuralNetworksMemory_createFromFd 是如何工作的?

c++ - Win32 C/C++ 从字节数组中读取 BMP 宽度和高度

c++ - 功放库错误

javascript - for 循环内的 while 循环串联

c++ - 如何在 Mac 上自动获取 C++ 程序的异常类型和消息?

c++ - shared_ptr : "call of an object of a class type without appropriate operator() or conversion function to pointer-to-function type"

java - 如何检查是否输入了四分之一的字符串?