Castellanos
Castellanos

Reputation: 157

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

The first iteration will work perfectly fine. I can enter the song title, artist, and rating. However, the next time, it will display "Enter the song title" AND "Enter the artist: " so that means I cannot enter a song title the next time up. I'm sure it's a simple mistake, but I can't find it. This is 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; 
    }
}

Upvotes: 2

Views: 126

Answers (1)

David G
David G

Reputation: 96835

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);

Upvotes: 3

Related Questions