When the user enters 'q' or 'Q' I want the program to exit the loop. What confuses me with this is that I'm taking in an integer so I'm unsure of how to stop it when a char is enter.
Currently it loops fine until I enter a 'Q' then it endlessly loops results. How can I accomplish this?
int main(){
// Create an instance of the DayOfYear class
DayOfYear dayOfYearObj;
int day; // To hold the day
bool stop = false;
// Display the purpose of the program.
cout << "This program converts a number \n"
<< "into a string representing the \n"
<< "month and day.\n\n";
while(stop == false)
{
// Get the day as input from the user.
cout << "\nEnter a whole number between 1 and 365: ";
cin >> day;
if( day == 'q' || day == 'Q')
{
stop = true;
}
else
{// Set the day.
dayOfYearObj.setDay(day);
// Display the object.
dayOfYearObj.print();
}
}
return 0;
}
Well inputting a char into an int will lead to undefined behavior. You could check if cin enters a fail state and then stop it then, but the program would be able to be stopped if anything other than a number was entered, not just q. Perhaps make day a char and then convert if not 'q'?
#include <iostream>
#include <sstream>
#include <string>
int
main()
{
// Loop condition is false if std::cin reads past the end-of-stream, or if an
// I/O error occurs
for (std::string token; std::cin >> token;) {
// Quit if q or Q is entered
if (token == "q" || token == "Q")
break;
int result;
{ // convert token to integer, or try again
std::istringstream ss{ token };
if (!(ss >> result))
continue;
}
std::cout << "read " << result << "\n";
}
}
If you are happy that input is just going to be an integer or a Q, and you are not worried about other failure conditions, then you could try cin.peek():