my program of registration and login encountered a few problems during output :
I have to register a new user and pass first(even if i alrd have previous usernames and passwords stored in the text file im trying to retrieve it from), after that only i can login using previous username and passwords and this repeats after i close the debug window and start debugging again (if i directly choose to login upon running the program, it will output "invalid username or password")
when logging out from a newly registered username, the program jumps to the
int main() AND DISPLAY "1. Register...."
but logging out from previous usernames, it jumps to
void login() and display "Username:"
*note: the last function isn't complete yet but i think it doesn't affect it (?) (the program worked fine before i added the void accountPage()tho)
*i am not supposed to use pointers plus i'm very new to c++
the code is a bit long but its just a lot of simple functions, i would rly appreciate it if someone can point out my mistake anywhere
#include <iomanip>
#include <cctype>
#include <fstream>
#include <string>
using namespace std;
//Global Variables
int Choice1;
int mobile, ic;
string user, pass, name, inUser, inPass;
//Function Prototypes
void register_user();
void login();
void bookRoom();
bool CheckCredentials(string, string);
void accountPage();
int main()
{
cout << "Welcome to Cozy Homes!\n";
cout << "Operating hours: 11am - 10pm Tuesday - Sunday\n\n\n\n";
do {
cout << "\n1. Register\n";
cout << "2. Log In\n";
cout << "3. Exit\n";
cout << "Please enter a number:";
cin >> Choice1;
if (Choice1 == 1)
{
register_user();
}
else if (Choice1 == 2)
{
login();
}
else if (Choice1 == 3)
{
cout << "Exiting now...\n";
return 0;
}
else if (Choice1 < 1 || Choice1 > 3)
{
cout << "Please choose a number from the menu!" << endl;
}
} while (Choice1 != 3);
system("pause");
return 0;
}
//Register page
void register_user()
{
cin.ignore();
cout << "\n\n\n" << "New Username: ";
getline(cin, user);
cout << endl;
cout << "New Password: ";
getline(cin, pass);
cout << endl;
cout << "Full name: ";
getline(cin, name);
cout << endl;
cout << "Mobile Number: ";
cin >> mobile;
cout << endl;
cout << "Ic Number (without \" - \"): ";
cin >> ic;
cout << endl;
cout << "Registered Successfully!" << endl;
cout << endl;
//Store username and password in login file
ofstream l("login.txt", ios::app);
if (!l.is_open()) {
cout << "could not open file \n";
}
l << user << " " << pass << endl;
l << endl;
l.close();
//Store other details in customer file
ofstream c("customer.txt", ios::app);
if (!c.is_open()) {
cout << "could not open file \n";
}
c << user << endl;
c << pass << endl;
c << name << endl;
c << mobile << endl;
c << ic << endl;
c << '\n';
c.close();
}
//Log in page
void login()
{
do
{
cout << "\nUsername: ";
cin >> inUser;
cout << "Password: ";
cin >> inPass;
if (CheckCredentials(inUser, inPass) == true)
{
cout << "\nLogin sucessful!" << endl;
cout << "Welcome, " << inUser << endl;
cout << endl;
accountPage(); // Redirects user to their account page after successfully logged in
}
else
cout << "\nInvalid username or password. " << endl;
} while (CheckCredentials(inUser, inPass) != true);
}
//Validate their username and password
bool CheckCredentials(string inUser, string inPass)
{
string u;
string p;
bool status = false;
ifstream f;
f.open("login.txt");
if (!f.is_open())
{
cout << "Unable to open file!\n";
}
else if (f)
{
while (!f.eof())
{
f >> u >> p;
if (inUser == u && inPass == p)
{
status = true;
}
else
{
status = false;
}
}
}
f.close();
return status;
}
//Account Page
void accountPage()
{
int Choice2;
do
{
cout << "1. Profile\n";
cout << "2. Book a Room\n";
cout << "3. Cancel Booking\n";
cout << "4. Logout\n";
cout << "Please enter a number: ";
cin >> Choice2;
if (Choice2 == 1)
{
}
else if (Choice2 == 2)
{
}
else if (Choice2 == 3)
{
}
else if (Choice2 == 4)
{
cout << "Logging out.....\n\n\n\n";
cout << endl;
}
} while (Choice2 != 4);
}
//Booking page
void bookRoom() {
cout << " ";
}
```
Like this :
void login()
{
bool loggedin = false;
while(!loggedin)
{
cout << "\nUsername: ";
cin >> inUser;
cout << "Password: ";
cin >> inPass;
if (CheckCredentials(inUser, inPass) == true)
{
loggedin = true;
cout << "\nLogin sucessful!" << endl;
cout << "Welcome, " << inUser << endl;
cout << endl;
accountPage(); // Redirects user to their account page after successfully logged in
}
else
cout << "\nInvalid username or password. " << endl;
}
}
or like this:
void login()
{
bool loggedin = false;
do
{
cout << "\nUsername: ";
cin >> inUser;
cout << "Password: ";
cin >> inPass;
if (CheckCredentials(inUser, inPass) == true)
{
loggedin = true;
cout << "\nLogin sucessful!" << endl;
cout << "Welcome, " << inUser << endl;
cout << endl;
accountPage(); // Redirects user to their account page after successfully logged in
}
else
cout << "\nInvalid username or password. " << endl;
}
while(!loggedin)
}
As this is a school assignment I did not bother to test the code myself.
It is just meant to get you futher and I did only minimal changes.
The point of your error is that the faulty function calls checkcredentials before a user and pasword is entered in the system.
If this solves your problem please mark as solution.
l << user << " " << pass << endl;
l << endl; <---- creates an empty line in your file. Is this intentional ?
l.close();
Clearly there is more bugs in your program. But this will get you further.
Have to do my own job now ;-)
Ok So I have abit of a problem with my code that I cant seem to find the solution for. Im writing a program that will work like a phonebook for your phone. And everything that happens will be saved in a .txt file. So when the program starts it will always read from the same file and put that into class objects called "person" and then you will be able to edit/delete/add new contacts and then it gets rewriten to the file.
The problem im having right now is that I want to make more of the code into functions instead of having it all in the main folder. So as you can see from the two last functions, one should read from the file and the other should write to the file. What I want to do is to replace all the code in main() that has to do with readToFile and writeToFile. Also i would like to be able to put the writeToFile function after every case switch action like edit/delete/add. So that you dont have to choose to write to the file. It just does that automatically.
Can I somehow use pointers/references for this or how do i get access to the "person" objects in my functions.
First time asking a question here so feel free to educate me if i did something wrong.
Here is the code:
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
void printline(char, int);
bool name_valid(string);
class contact
{
public:
string fName, lName, adress, epost, mobileNo, birthday;
//initialize the contact by a default value
contact() : fName(""), lName(""), adress(""), epost(""), mobileNo(""), birthday("")
{}
// Write all contacts to the file.
bool writeToFile()
{
if (fName != "")
{
cout << "Name: " << fName << " " << lName << "\n" << "Mobilenumber: " << mobileNo << "\n" << "Adress: " << adress << "\n" << "Email: " << epost << "\n" << "Birthday: " << birthday << endl;
return 1; //Success!!
}
else
{
cout << " Fail!" << endl;
return 0; //Fail!!
}
}
//Show all contacts
bool showAll()
{
if (fName != "")
{
cout << "Name: " << fName << " " << lName << "\n" << "Mobilenumber: " << mobileNo << "\n" << "Adress: " << adress << "\n" << "Email: " << epost << "\n" << "Birthday: " << birthday << endl;
return 1; //Success!!
}
else
return 0; //Fail!!
}
// Search
bool Search(string search_word)
{
if (search_word == fName)
{
cout << "Name: " << fName << " " << lName << "\n" << "Mobilenumber: " << mobileNo << "\n" << "Adress: " << adress << "\n" << "Email: " << epost << "\n" << "Birthday: " << birthday << endl;
return 1;
}
else
return 0;
}
// Check if a name exists or not
bool name_exists(string tname)
{
if (tname == fName)
return 1;
else
return 0;
}
// The contact object is initialized by valid values
bool addContact(string new_fName, string new_lName, string new_adress, string new_epost, string new_mobileNo, string new_birthday )
{
if (fName == "")
{
fName = new_fName;
lName = new_lName;
adress = new_adress;
epost = new_epost;
mobileNo = new_mobileNo;
birthday = new_birthday;
return 1; // Success !!
}
else
return 0; // Failure !!
}
//edits the contact details
bool edit(string);
bool erase(string new_name)
{
if (new_name == fName)
{
fName = "";
lName = "";
adress = "";
epost = "";
mobileNo = "";
birthday = "";
return 1;
}
else
return 0;
}
};
// Edits the contact
bool contact::edit(string name_check)
{
string new_fName, new_lName, new_adress, new_epost, new_mobileNo, new_birthday;
if (name_check == fName)
{
cin.ignore();
cin.clear();
cout << "Enter new first name: ";
getline(cin,new_fName);
cout << "Enter new lastname: ";
getline(cin,new_lName);
cout << "Enter new adress: ";
getline(cin,new_adress);
cout << "Enter new epost: ";
getline(cin,new_epost);
cout << "Enter new birthday: ";
getline(cin,new_birthday);
fName = new_fName;
lName = new_lName;
adress = new_adress;
epost = new_epost;
birthday = new_birthday;
return 1;
}
else
return 0;
}
int main()
{
contact person[100];
ifstream infile("Phonebook.txt");
string temp_fName, temp_lName, temp_adress, temp_epost, temp_mobilNo, temp_birthday;
int counter, choice, i;
bool flag;
bool cancel_flag;
// Read from file to contact person
string ignoreName, ignoreCell, ignoreAdress, ignoreEmail, ignoreBirthday;
string fileFirstname, fileLastname, fileCell, fileAdress, fileEmail, fileBirthday;
// Goes through the text file and put all the names in the contact class
while (!infile.eof())
{
getline(infile, ignoreName, ' ');
getline(infile, fileFirstname, ' ');
getline(infile, fileLastname);
getline(infile, ignoreCell, ' ');
getline(infile, fileCell);
getline(infile, ignoreAdress, ' ');
getline(infile, fileAdress);
getline(infile, ignoreEmail, ' ');
getline(infile, fileEmail);
getline(infile, ignoreBirthday, ' ');
getline(infile, fileBirthday);
// Check if the file is empty
if (!infile)
{
break;
}
for (i = 0; i < 100; i++)
if (person[i].addContact(fileFirstname, fileLastname, fileAdress, fileEmail, fileCell, fileBirthday))
{
cout << "\nContact added successfully!" << endl;
flag = 1;
break;
}
}
infile.close();
ofstream outfile("Phonebook.txt");
cout << "=========== Your Phonebook ==========" << endl;
do
{
cout << "\n\n";
printline('-', 25);
cout << "1. Add Contact" << endl
<< "2. Edit Contact" << endl
<< "3. Delete Contact" << endl
<< "4. Search" << endl
<< "5. Show All Contacts" << endl
<< "6. Write All Contacts To File." << endl
<< "0. Exit" << endl << endl
<< "Your choice... ";
cin >> choice;
system("cls");
printline('-', 20);
cancel_flag = 0;
flag = 0;
counter = 0;
switch (choice)
{
case 0:
return 0;
break;
// Adds a new contact
case 1:
cout << "Add New Contact\t\t\t\tpress - to cancel" << endl;
printline('-', 25);
counter = 0;
// Loop until correct contact info is untered
do
{
flag = 0;
if (counter)
cout << "Try again \t\t\t\tpress - to cancel" << endl;
//count how many times the do-while loop executes
counter++;
cin.ignore();
cin.clear();
cout << "First Name: ";
getline(cin, temp_fName);
cout << "Last Name: ";
getline(cin, temp_lName);
cout << "Adress: ";
getline(cin, temp_adress);
cout << "Email: ";
getline(cin, temp_epost);
cout << "Mobile Number: ";
getline(cin, temp_mobilNo);
cout << "Birthday: ";
getline(cin, temp_birthday);
if (temp_fName == "-")
{
cancel_flag = 1;
break;
}
for (i = 0; i < 100; i++)
{
if (person[i].name_exists(temp_fName))
{
cout << "The name you entered is already there"
"in the phonebook, entere a different name." << endl;
flag = 1;
break;
}
}
} while (!name_valid(temp_fName) || flag);
if (cancel_flag)
{
system("cls");
break;
}
//This loop adds the contact to the phonebook
for (i = 0; i < 100; i++)
if(person[i].addContact(temp_fName, temp_lName, temp_adress, temp_epost, temp_mobilNo, temp_birthday))
{
cout << "\nContact added successfully!" << endl;
flag = 1;
break;
}
if (!flag)
cout << "Memory full! Delete some contacts first." << endl;
break;
// Edits an existing contact
case 2:
cout << "Enter a contact name to edit \t\t\t\tpress - to cancel" << endl;
cin >> temp_fName;
// Cancel operation
if (temp_fName == "-")
{
system("cls");
break;
}
for (i = 0; i < 100; i++)
if (person[i].edit(temp_fName))
{
cout << "Edited Successfully!" << endl;
flag = 1;
break;
}
if (!flag)
cout << "Contact name not found!" << endl;
break;
//Delete a contact
case 3:
do
{
if (counter)
cout << "Try again" << endl;
counter++;
cout << "Enter a contact name to delete: \t\t\t\tpress - to cancel" << endl;
cin >> temp_fName;
// Cancel operation
if (temp_fName == "-")
{
system("cls");
break;
}
//Final Confirmation
for (i = 0; i < 100; i++)
if (person[i].name_exists(temp_fName))
{
flag = 1;
cout << "Are you sure you want to delete (1/0)" << endl;
int yes;
cin >> yes;
if (!yes)
{
system("cls");
cancel_flag = 1;
}
break;
}
if (!flag)
cout << "Contact name not found!" << endl;
if (cancel_flag)
break;
// This code deletes the contact
if (flag)
{
for (i = 0; i < 100; i++)
if (person[i].erase(temp_fName))
{
cout << "Deleted successfully!" << endl;
break;
}
}
} while (!flag);
break;
// Search a contact
case 4:
do
{
if (counter)
cout << "Try again" << endl;
counter++;
cout << "Search a name: \t\t\t\tpress - to cancel" << endl;
cin >> temp_fName;
// Cancel operation
if (temp_fName == "-")
{
system("cls");
break;
}
for (i = 0; i < 100; i++)
if (person[i].Search(temp_fName))
{
flag = 1;
break;
}
if (!flag)
cout << "Contact namew not found!" << endl;
} while (!flag);
break;
// Show all the contacts
case 5:
cout << "Showing Contacts" << endl;
printline('-', 25);
for (i = 0; i < 100; i++)
{
if (person[i].showAll())
{
flag = 1;
cout << "\n\n";
}
}
if (!flag)
cout << "No contacts found!" << endl;
break;
case 6:
// Write to file
cout << "Writing to file." << endl;
printline('-', 25);
for (int i = 0; i < 100; i++)
{
if (person[i].fName != "")
{
outfile << "Name: " << person[i].fName << " " << person[i].lName << "\n" << "Mobilenumber: " << person[i].mobileNo << "\n" << "Adress: " << person[i].adress << "\n" << "Email: " << person[i].epost << "\n" << "Birthday: " << person[i].birthday << "\n\n\n\n";
flag = 1;
cout << "\n\n";
}
}
break;
}
}while (1);
return 0;
}
//prints a line
void printline(char ch, int size)
{
for (int i = 0; i < size; i++)
cout << ch;
cout << "\n";
}
//Contact name validation
bool name_valid(string tname)
{
if (tname.size() > 20)
{
cout << "Invalid name!\nEnter a name within 20 characters!" << endl;
return 0;
}
else if (tname == "")
{
cout << "Invalid Name!\nName cannot be blank" << endl;
return 0;
}
else
return 1;
}
void writeToFile()
{
cout << "Writing to file." << endl;
printline('-', 25);
for (int i = 0; i < 100; i++)
{
if (person[i].fName != "")
{
outfile << "Name: " << person[i].fName << " " << person[i].lName << "\n" << "Mobilenumber: " << person[i].mobileNo << "\n" << "Adress: " << person[i].adress << "\n" << "Email: " << person[i].epost << "\n" << "Birthday: " << person[i].birthday << "\n\n\n\n";
flag = 1;
cout << "\n\n";
}
}
}
void readfromfile()
{
ifstream infile("Phonebook.txt");
string ignoreName, ignoreCell, ignoreAdress, ignoreEmail, ignoreBirthday;
string fileFirstname, fileLastname, fileCell, fileAdress, fileEmail, fileBirthday;
// Goes through the text file and put all the names in the contact class
while (!infile.eof())
{
getline(infile, ignoreName, ' ');
getline(infile, fileFirstname, ' ');
getline(infile, fileLastname);
getline(infile, ignoreCell, ' ');
getline(infile, fileCell);
getline(infile, ignoreAdress, ' ');
getline(infile, fileAdress);
getline(infile, ignoreEmail, ' ');
getline(infile, fileEmail);
getline(infile, ignoreBirthday, ' ');
getline(infile, fileBirthday);
// Check if the file is empty
if (!infile)
{
break;
}
for (int i = 0; i < 100; i++)
if (person[i].addContact(fileFirstname, fileLastname, fileAdress, fileEmail, fileCell, fileBirthday))
{
cout << "\nContact added successfully!" << endl;
flag = 1;
break;
}
}
infile.close();
}
Just pass in an array to the function (and others which are needed). Now the size of the array is known beforehand so we can protect it from array decay too. It'll look something like this,
void writeToFile(contact(&person)[100], std::fstream& outfile, bool& flag) { ... }
void readfromfile(contact(&person)[100], bool& flag) { ... }
Note that were passing in the others (flag and outfile) using the reference so that the actual variable can be altered.
From the two, I would recommend using the second option. Its clean, simple and safe (if you may).
Note: Try not to use using namespace std;. It not a good practice and basically your taking the std namespace and putting it in the global namespace. Now that namespace is huuuuggeeeeee. Later to access its objects and stuff, use :: operator.
So i have this funcion that asks for input if player wants to play again ->
bool AskToPlayAgain()
{
cout << "Play again?\n";
string PlayerResponse = "";
getline(cin, PlayerResponse);
cout << "First Character: " << PlayerResponse[0];
cout << endl;
return false; }
This function works on its own, but i put it after my main game function it just skips it. My main game function is -->
void PlayGame(){
Initialize();
for (int i = 0; i < 5; i++)
{
cout << "Introduce your word guess in 5 attempts: \n";
cin >> GuessWord;
if (GuessWord == Word)
{
cout << "Correct Guess!!!\n";
}
else
{
cout << "Wrong Guess!!!\n";
cout << endl;
}
}
cout << "Correct word is " << Word;
cout << endl;
return;}
So yes, not sure why it does that.
I was writing this code for training, and I'm in a problem where if my user write his name followed by a space and something else, the program will mess up my flow. So it's easier if you try the little program and when it ask for name, put like "Robert Red". The problem occurs just when you put something else after the space, if you input just "Robert" all goes good.
This is the code:
// Description: This is a simple replica of the Japanese game Rock, Paper and
// Scissors.
// Author: Ernesto Campese
// Last Update: 11/04/2018
// Version: 0.0.1
#include "std_lib_facilities.h"
int main() {
string username = "";
char userinput;
int rounds = 0;
int wins = 0;
int draws = 0;
int loses = 0;
int user_secret = 0;
vector<string> options = {"Paper", "Scissors", "Rock"};
cout << "Enter your name: ";
cin >> username;
cout << "Welcome " << username << ", this is the game of Rock, Paper and Scissors.\n";
cout << username << " how many rounds you want to do? ";
cin >> rounds;
if (rounds <= 0) {
cout << "You need to play at least one round!\n";
rounds++;
}
cout << "The game is based on " << rounds << " rounds, you versus the CPU.\n";
cout << "Are you ready? (y/n): ";
cin >> userinput;
if (userinput != 'y') {
cout << "\nThank you.\nProgram Terminated by " << username;
return 0;
}
for(int i = 1; i <= rounds; i++) {
// Title of the rounds
if (i == 1) {
cout << "\nLet's start the first round!\n";
} else {
cout << "Round n. " << i << " begins!\n";
}
// USER makes a move
cout << "Which is your move? (r,p,s): ";
cin >> userinput;
cout << '\n' << username << " says... ";
switch (userinput) {
case 'r':
cout << "Rock\n";
user_secret = 2;
break;
case 'p':
cout << "Paper\n";
user_secret = 0;
break;
case 's':
cout << "Scissors\n";
user_secret = 1;
break;
default:
cout << "something weird...\n";
break;
}
// CPU makes a move
int cpu_secret = rand() % 3;
cout << "CPU says... " << options[cpu_secret] << "!\n";
// The program calculates the result.
if (user_secret == cpu_secret) {
draws++;
cout << username << " and the CPU draws!\n\n";
} else if (user_secret == 0 && cpu_secret == 2) {
wins++;
cout << username << " wins!\n\n";
} else if (user_secret == 1 && cpu_secret == 0) {
wins++;
cout << username << " wins!\n\n";
} else if (user_secret == 2 && cpu_secret == 1) {
wins++;
cout << username << " wins!\n\n";
} else {
loses++;
cout << username << " lose!\n\n";
}
}
cout << "\n\nBattle End!\n";
if (wins > loses) {
cout << username << " won the battle!\n";
} else if (loses > wins) {
cout << username << " lost the battle!\n";
} else {
cout << username << " draws the battle!\n";
}
cout << "Thank you " << username << "!\n";
}
You can try it here: Try me
Thank you!
operator>> stops reading input when it finds a whitespace character.
Use std::getline() to read user input with spaces.
Example using your code:
cout << "Enter your name: ";
getline(cin, username);
If you want the user to be able to type in a name that has spaces in it, use std::getline() instead of operator>>:
getline(cin, username);
Otherwise, if you want the user to enter only 1 word for the name, and you want to ignore anything else the user may enter, use std::cin.ignore():
#include <limits>
...
cin >> username;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
Alternatively, you can use std::getline() to read a line, and then use std::istringstream with operator>> to extract the 1st word of the line:
#include <sstream>
...
string line;
getline(cin, line);
istringstream(line) >> username;
In C++, I'm trying to input movie's names and years of releasing and store them in a database/structure. Before I ask for the titles and years to be inputted. I have the user log on with credentials. In this case, the username is "rusty" and the password is "rusty".
The issue I'm having is the after the credentials are verified, the first movie title to input into the database/structure is skipped. I believe this has something to do with me using the _getch function, but I'm not totally sure.
My code is below. My output looks like this:
Please enter your username
rusty
Please enter your password
Access granted! Welcome rusty
Enter title: Enter year: (input movie year)
Enter title: (input movie title)
Enter year: (input movie year)
Enter title: (input movie title)
....
#include <iostream>
#include <string>
#include <sstream>
#include <conio.h>
using namespace std;
//function prototype
int username_and_pass();
#define NUM_MOVIES 6
struct movies_list{
string title;
int year;
}films[NUM_MOVIES];
// prototype with function declaration
void sort_on_title(movies_list films[], int n)
{
movies_list temp;
for (int i = 0; i < n - 1; i++)
{
if (films[i].title>films[i + 1].title)
{
temp = films[i];
films[i] = films[i + 1];
films[i + 1] = temp;
}
}
}// end of sort_on_title function
void printmovie(movies_list movie)
{
cout << movie.title;
cout << " (" << movie.year << ") \n";
}
void search_on_title(movies_list films[], int n, string title)
{
bool flag = false;
for (n = 0; n < NUM_MOVIES; n++)
{
if (films[n].title == title)
{
cout << "Title: " << films[n].title << endl;
cout << "Year of Release: " << films[n].year << endl;
cout << "\n";
flag = true;
}
}
if (flag == false)
cout << "Search on title not found!" << endl;
}// end of search_on_title function
void search_on_year(movies_list films[], int n, int year)
{
bool flag = false; // check on existence of record
for (n = 0; n < NUM_MOVIES; n++)
{
if (films[n].year == year) // display if true
{
cout << "Title: " << films[n].title << endl;
cout << "Year of Release: " << films[n].year << endl;
cout << "\n";
flag = true;
}
}
if (flag = false)
cout << "Search on title not found!" << endl;
}// end of search_on_title function
int menu()
{
int choice;
cout << " " << endl;
cout << "Enter 1 to search on titles " << endl;
cout << "Enter 2 to search on years " << endl;
cin >> choice;
cout << "\n";
return choice;
}// end of menu function
int username_and_pass()
{
string uName;
string password;
int value;
char ch;
cout << "Please enter your username\n";//"rusty"
cin >> uName;
cout << "Please enter your password\n";//"rusty"
ch = _getch();
while (ch != 13)//As long as the user doesn't press Enter
{//(enter is ASCII code 13) continue reading keystrokes from the screen.
password.push_back(ch);
cout << '*';
ch = _getch();
}
if (uName == "rusty" && password == "rusty")
{
cout << "\n\nAccess granted! Welcome " << uName << "\n\n" << endl;
value = 1
}
else
{
cout << "Invalid credentials" << endl;
value = 0;
}
return value;
}// end of username_and_pass function
int main()
{
string mystr;
int n;
string response;
int value = 0;
do
{
value = username_and_pass();
} while (value==0);
if(value==1)
{
for (n = 0; n < NUM_MOVIES; n++)
{
cout << "Enter title: ";
getline(cin, films[n].title);
cout << "Enter year: ";
getline(cin, mystr);
stringstream(mystr) >> films[n].year;
}
//sorts records
sort_on_title(films, NUM_MOVIES);
cout << "\nYou have entered these movies:\n";
for (n = 0; n < NUM_MOVIES; n++)
printmovie(films[n]);
//menu
int choice = 0;
choice = menu();
if (choice == 1)
{
string searchTerm;
cout << "What is the movie you want to search for? " << endl;
cin >> searchTerm;
cout << " " << endl;
search_on_title(films, NUM_MOVIES, searchTerm);
}
else
{
int searchTermYear;
cout << "What is the year you want to search for? " << endl;
cin >> searchTermYear;
cout << " " << endl;
search_on_year(films, NUM_MOVIES, searchTermYear);
}
cout << "Would you like to query the database again? (Y/N)" << endl;
cin >> response;
if (response == "Y" || "y")
{
choice = menu();
if (choice == 1)
{
string searchTerm;
cout << "What is the movie you want to search for? " << endl;
cin >> searchTerm;
cout << " " << endl;
search_on_title(films, NUM_MOVIES, searchTerm);
}
else
{
int searchTermYear;
cout << "What is the year you want to search for? " << endl;
cin >> searchTermYear;
cout << " " << endl;
search_on_year(films, NUM_MOVIES, searchTermYear);
}
}
}
return 0;
}
Flush all the content's of input buffer.
Please go to following link to flush contents of input buffer.
https://stackoverflow.com/a/7898516/4112271
I am not sure what causing you this problem.But can you try using cin.clear(). Place it before you ask for input of title.
cin.clear();
cout << "Enter title: ";
getline(cin, films[n].title);
cout << "Enter year: ";
getline(cin, mystr);
stringstream(mystr) >> films[n].year;