In my previous question, I got this answer to work so that if the user inputs more than 5 characters in the nation name, it will output an error.
#include <iostream>
#include <iomanip>
int main()
{
using namespace std;
const int maxchar = 5;
string nationname;
cout << "What is the name of your nation?" << endl;
cin >> nationname;
if (nationname.size() > maxchar)
{
cout << "The input is too long." << endl;
return 1;
}
}
I want it so that it will loop back to the "cout << what is the name..." after it outputs the error.
Thanks!
Someone answered on my previous question how in the comments but I didn't get it to work/I don't know how or where to put it in my code.
At least to me, the responses you've gotten so far look a little clumsy. IMO, this calls for the little-used, much-neglected do/while loop:
bool show_error() {
return std::cout << "The input is too long.\n";
}
int main() {
static const int maxchar = 5;
std::string nationname;
do {
std::cout << "What is the name of your nation?\n";
} while (std::cin >> nationname && nationname.size() > maxchar && show_error());
}
As to why I think this is better: first of all, unless it's completely unreasonable to do so, it's much better to write the condition for a loop as the loop condition, rather than a while (1)
followed by a conditional break
somewhere inside the loop. Second, if you always want a loop to execute at least once, a do
/while
loop is the right one for the job. A while
loop should be used when there's a reasonable chance the loop will not execute at all (when/if the condition is false). Finally, although it's arguably a fairly minor point, this also tests the result of each input and output operation, and breaks out of the loop if either fails. If you don't do that, incorrect input can lead to an infinite loop, where the attempt to read fails, but leaves the data in the input stream, so the next iteration will fail again (without waiting for the user to enter more data).
As an aside: I'd advise against using std::endl
so much (or probably at all). Get in the habit of using \n
when you just want a new-line, and std::flush
when/if you want to flush the stream.