getline and while error in C++ - c++

Hi I am a beginner for C++, and here is my practice code:
cout << "Hello World! "<< "Please enter your name" << " ";
//cin >> i;
getline(cin, mystring);
stringstream(mystring) >> name;
cout << "Please enter your password"<< " " ;
getline(cin, mystring);
stringstream(mystring) >> password;
cout << password << endl;
do {
cout << "Sorry, your password does not match your name, please enter the password again" << " " << endl;
getline(cin, mystring);
stringstream(mystring) >> password;
} while (!(name == "victor" & password == "victor"));
I wonder why the result is as follows that "Sorry..." appears even the password is correct?
Hello World! Please enter your name victor
Please enter your password victor
victor
Sorry, your password does not match your name, please
enter the password again

A do...while loop always executes at least once because the test at the bottom is performed at the end of the loop.
So you will always see the message about the wrong password at least once. If you want to execute the loop only when the condition is true, use a regular while loop with the condition at the top.
Also, the logic AND operator is && and not &.
while (!(name == "victor" && password == "victor"));
{
cout << "Sorry, your password does not match your name, please enter the password again" << " " << endl;
getline(cin, mystring);
stringstream(mystring) >> password;
}

Related

I am making a quiz-like program. I already wrote the string answer ="George Washington". but when the user inputted the answer, it's wrong

answer = "George";
cout << "\t\t\t\t\t Who was the first President of United States?" << endl;
cout << "";
cout << "";
cout << "Congrats " << player1_name << " (Player1). Now, type in your answer:";
cin >> player1_answer;
if (player1_answer == answer){
cout << "check";
}else{
cout << "x";
}
This is my code. But when the user inputted the answer as exactly as what was written in the answer variable, it outputs 'x'. But if the user inputted the same answer excluding the space between "George" and "Washington", it outputs 'check'. What should I do so that the program will accept the space in the answer inputted by the user?
I tried searching the web but I can't understand a thing. So please help me
You can simply use getline instead of cin. cin reads the user input up until the first whitespace character (most commonly newlines or spaces), but getline will read user input until they hit enter. Because of this, if you want to get user input that includes spaces, you should use getline (or something similar) instead of cin.
Instead of
cin >> player1_answer;
you should use
getline(cin, player1_answer);
By using getline, the full user input ("George Washington") get assigned to the variable player1_answer. With cin, only "George" was being used, because it stopped listening for input after the first space.
Here is a full, working code example:
#include <iostream>
using namespace std;
string answer = "George Washington";
string player1_name = "Steve";
string player1_answer;
cout << "\t\t\t\t\t Who was the first President of United States?" << endl;
cout << "";
cout << "";
cout << "Congrats " << player1_name << " (Player1). Now, type in your answer:";
getline(cin, player1_answer); //Enter "George Washington"
if (player1_answer == answer){
cout << "check";
}else{
cout << "x";
}
//"check"
return -1;

How do I make my program only react to yes or no answers?

I was wondering how I'd be able to make my program reply to unknown answers that arent yes or no questions, when I ask them their name and they respond, they can say it is their name or its not and are given the chance to retype it until they confirm that is their name(test my code to see what I mean) but when it re asks them what their name is and says "oh, so your name is?" it just looks like the computer skips past their response and asks the question again, but i want the program to say "sorry i don't understand that" THEN re ask the question. Now what I'm wondering is how I can make it to where the computer responds with an error message to there wrong or misunderstood answer
#include <string>
using namespace std;
string Name;
}
int main() {
double age;
cout << "what is your name?"<< endl;
getline(cin, Name);
cout << "your name is " << Name << "?, is that correct? Y/N"<< endl;
string answer;
getline(cin, answer);
if (answer == "yes") {
cout << "thanks for the information" << endl;
}
if (answer == "no"){
do {
cout << "oh ok, what is your name then?"<< endl;
getline(cin,Name);
cout<< "oh so your name is " + Name << "? Y/N"<< endl;
getline(cin, answer);
}
while(answer <= "no");{
}
}
cout << "how old are you?" << endl;
cin >> age;
cout << "your name is "<< Name << " and you are " << age << " years old"<< endl;
return 0;
}
You are on the right track using "if" statements and "while" loops. You just need to improve your understanding of the while loop & if-else statements, then with a few edits you can get your code working.
Firstly, you are prompting the user for "Y/N", but then you are trying to test for "yes" or "no". This is will be very confusing for the user, who is trying to enter a 'Y' or a 'N' and not getting anywhere. You should pick one or the other. In this case I will assume you want to proceed with "Y/N".
First, take a look at your use of the while loop.
For the while condition, you have used a <= sign, which is testing for "less than or equal to". In this context, you probably want to test for equality (==) or non-equality (!=).
You haven't placed any statements within the body of the while loop (i.e. inside the curly braces {} ). A while loop will only execute the code within the curly braces.
For your program, you only need to re-prompt the user if they answer with anything other than a 'Y'. Then you want to keep prompting the user until they enter a 'Y'... a while loop is perfect for this. To make this work, your condition for the loop should be (assuming you want to test for upper and lower case input):
while (answer != "y" || answer != "Y") {
}
Now, any code you put inside the curly braces {} will continue to loop until the user inputs 'y' or "Y".
Next, have a look at your use of if statements.
Your first if statement tests the input for "yes".
Your second if statement tests the input for "no".
The problem with this, is that if neither "yes" or "no" are input, no code will be executed.
The key is changing your second "if" statement to an "else". The "else" will act as a catch all - if anything is entered outside of the program's scope, the else statement will catch it and re-prompt the user..
Finally you want to place the if-else statements inside the while loop - then you can be sure the user will continue to be prompted until they enter a 'Y'.
I have altered your code so that it now provides the desired behavior:
#include <iostream>
#include <string>
using namespace std;
int main() {
cout << "What is your name?" << endl;
string name {};
getline (cin, name);
cout << "Your name is: " << name << ". Is that correct? Y/N: " << endl;
string answer {};
getline(cin, answer);
while (answer != "y" && answer != "Y") {
if (answer == "n" || answer == "N") {
cout << "Oh, ok, what is your name then? " << endl;
getline (cin, name);
cout << "Oh, so your name is " << name << "? Y/N: " << endl;
getline (cin, answer);
}
else {
cout << "Sorry... I don't understand that. Please enter 'Y' or 'N'..." << endl;
cout << "Your name is: " << name << ". Is that correct? Y/N: " << endl;
getline (cin, answer);
}
}
cout << "How old are you? " << endl;
int age {};
cin >> age;
cout << "Thanks, so your name is "<< name << " and you are " << age << " years old" << endl;
return 0;
}

Output a value to console after do...while statement is satisfied?

I'm extremely new to C++, and can't really figure this out. I've tried a couple things, but I feel like I'm just missing something simple.
I have this console application where a user inputs a pre-defined password. If the password is incorrect, it prompts them to re-enter the password. If the password is correct, is simply ends the program, but I want it to say "Access granted!" then end.
A side issue I'm having is when more than word is entered as the password, "Access Denied" is printed for each word.
string password;
cout << "Please enter the password!" << endl;
cin >> password;
if (password == "test") {
cout << "Access granted!";
} else {
do {
cout << "Access denied! Try again." << endl;
cin >> password;
} while (password != "test");
}
return 0;
You need to output your "Access granted" message after the loop exits, and you also need to clear the stdin input after each failed attempt to discard any words that are still waiting to be read:
#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
Which would be better written like this instead:
#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;
Live Demo
However, note that operator>> reads only 1 word at a time, so something like "test I GOT IN!" will also be accepted. You should use std::getline() instead to read an entire line at a time, instead of reading a word at a time:
#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;
Live Demo

Ask user for specified amount of characters?

I am new to C++ and I want to prompt the user to enter 10 characters exactly, anything more will just be ignored for example:
Please enter 10 characters:
123412341234
You entered: 1234123412
//and the 34 will be ignored because they entered more than 10
I got to here now:
string userInput;
cout << "Please enter 10 characters!\n";
cin >> userInput;
cout << "You entered: "<< userInput << endl;
Thank you everyone. Hope I am as accurate as I can be.
Just ask the user to enter a string and then take the substring of that
std::string userInput;
std::cout << "Please enter 10 characters: ";
std::cin >> userInput;
if(userInput.length() > 10)
{
userInput = userInput.substr(0, 10);
}
std::cout << "You entered: " << userInput << std::endl;

How to stop a while loop

This while loop never ends. For example, when i enter a wrong password it will keep on going to the "incorrect password" part over and over again.
Logo();
inFile.open("UsernamePassword.txt");
if (!inFile)
cout << "Unable to Open File";
else
{
cout << endl << endl << endl;
cout << " Please enter username: ";
cin >> user;
cout << " Please enter password: ";
cin >> pass;
while (username != user)
{
inFile >> username >> password;
if (user == username && pass == password)
{
cout << endl;
cout << "Welcome to CherryLunch!" << endl;
system("pause");
system("cls");
MainMenu();
}
else
{
cout << endl;
cout << " Invalid Username or Password!" << endl << endl;
system("pause");
system("cls");
}
}
}
inFile.close();
The while loop is infinite because you never allow the user to input a new password or username. When the if statement fails, it will return to loop header (where it will still be wrong) and continue onwards.
Give the user a chance to enter in a new user/pass combo and then the loop can still be finite (provided the user eventually provides the correct credentials).
move the cout and cin statements inside the while loop:
else
{
while (username != user)
{
cout << endl << endl << endl;
cout << " Please enter username: ";
cin >> user;
cout << " Please enter password: ";
cin >> pass;
inFile >> username >> password;
if (user == username && pass == password)
{
cout << endl;
cout << "Welcome to CherryLunch!" << endl;
system("pause");
system("cls");
MainMenu();
}
else
{
cout << endl;
cout << " Invalid Username or Password!" << endl << endl;
system("pause");
system("cls");
}
}
}
inFile.close();
It keeps on an infinite loop because you never ask if you reached the end of the file, so, if the file does not contain a username/password combination that matches the pair entered by the user, when the end of the file is reached, the line:
inFile >> username >> password;
Fails and username and password will contain the last entries seen on UsernamePassword.txt and the loop goes forever.
The following implementation of your program will test for the eof in the inFile file object:
#include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
int main() {
std::ifstream inFile;
std::string user, pass;
std::string username, password;
inFile.open("UsernamePassword.txt");
if (!inFile) {
std::cout << "Unable to Open File";
} else {
std::cout << std::endl << std::endl << std::endl;
std::cout << " Please enter username: ";
std::cin >> user;
std::cout << " Please enter password: ";
std::cin >> pass;
while (username != user && !inFile.eof()) {
inFile >> username >> password;
if (user == username && pass == password) {
std::cout << std::endl;
std::cout << "Welcome to CherryLunch!" << std::endl;
// Equivalent to the 'pause' command in linux
system("read -p 'Press any key to continue...' key");
// Equivalent to the 'cls' command in linux
system("clear");
// MainMenu();
} else {
std::cout << std::endl;
std::cout << " Invalid Username or Password!" << std::endl << std::endl;
system("read -p 'Press any key to continue...' key");
system("clear");
}
}
}
inFile.close();
}
You are trying to check for the username and password from the user and compare with all the usernames and passwords in the file.
Your approach seems fine. But you are printing "Invalid username..." after each comparison, not comparing all the usernames in the file. Hence move this output outside else block and place it in the while loop.
infile checks each line separately.
And also check the end of file.If the username and password are not found till the end of file, then print "Invald username" and provide the user to enter another set of name and password
Hope this helps!!
First, read the correct usernames and passwords from the file and save them in memory. That way, if the username/password validation fails the first time, you don't have to reopen or seek-to-beginning-in the file before checking on the next username/password typed by the user....
std::map usernames_passwords;
std::string username, password;
if (ifstream in("UsernamePassword.txt"))
while (in >> username >> password)
usernames_passwords[username] = password;
else
{
std::cerr << "Unable to open username/password file\n";
exit(EXIT_FAILURE);
}
Then prompt for login details until they're valid:
bool logged_in = false;
while (!logged_in &&
std::cout << "\n\n\n Please enter username: " &&
std::cin >> username &&
std::cout << " Please enter password: " &&
std::cin >> password)
{
// look for a match in the earlier-read login details...
auto it = usernames_passwords.find(username);
logged_in = it != std::end(usernames_passwords) && it->second == password;
}
// the while loop could also exit because "cin >>" failed, indicating EOF
// that could be because the user typed e.g. ^D (UNIX) or ^Z (Windows), or
// input was from a redirected file or pipe or over a network connection...
if (!logged_in)
{
std::cerr << "error reading login details from stdin\n";
exit(EXIT_FAILURE);
}
...ok - we know the username/password are good - do whatever else...