Вам необходимо вывести ваше сообщение "Access granted"
после выхода из цикла, а также вам необходимо очищать ввод stdin после каждой неудачной попытки отбросить все слова, которые все еще ожидают чтения:
#include <limits>
string password;
cout << "Please enter the password!" << endl;
cin >> password;
if (password == "test") {
cout << "Access granted!";
} else {
do {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Access denied! Try again." << endl;
cin >> password;
} while (password != "test");
cout << "Access granted!";
}
return 0;
Live Demo
Что было бы лучше написать так:
#include <limits>
string password;
cout << "Please enter the password!" << endl;
do {
cin >> password;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
if (password == "test") break;
cout << "Access denied! Try again." << endl;
}
while (true);
cout << "Access granted!";
return 0;
Демонстрационная версия
Однако обратите внимание, что operator>>
читает только 1 слово за раз, поэтому что-то вроде "test I GOT IN!"
также будет принято. Вы должны использовать std::getline()
вместо того, чтобы читать всю строку за раз, вместо того, чтобы читать слово за раз:
#include <limits>
string password;
cout << "Please enter the password!" << endl;
do {
getline(cin, password);
if (password == "test") break;
cout << "Access denied! Try again." << endl;
}
while (true);
cout << "Access granted!";
return 0;
Демоверсия