Reputation: 57
I want to extract 6 chars (including '\n') from input to an array and ensure that the input is correct by getting the new line character at an specific place in the array. This is what I did but I cant fix it. If the user enters more than 5 characters the loop repeats but the remaining characters still are in the stream. With the cin.ignore('\n') I get an infinite loop with no character in the stream.
do
{
cout << "Please log in: \n";
cin.get(username, 6);
cin.ignore('\n');
if (username[5] != '\n')
cout << "\nYour username should be 5 digits!\n\n";
} while (username[5] != '\n');
Upvotes: 0
Views: 836
Reputation: 5721
Unless you really want to do character-by-character entry, consider using a string and then making sure your input is valid. That would simplify the code a lot and make it easier to maintain:
string username;
if (cin >> username) {
if (username.length() != 5) {
// report bad input
}
}
Upvotes: 2
Reputation: 2316
What you are trying to do can be done much easier using strings, it is simply like this :
string username = "";
do
{
cout << "Please log in: \n";
cin>>username ;
if (username.length() != 5)
cout << "\nYour username should be 5 digits!\n\n";
} while (username.length() != 5);
but don't forget to add #include<string>
to your code
Upvotes: 1