C++ my program reads backspace as a character - c++

I am working with a c++ program, but I am stuck with annoying bug. The bug is that when i type the password, it counts backspace as a character so can I fix it? Here is the code.
#include <iostream>
#include <conio.h>
using namespace std;
int main() {
string password, username, lon, nu, np;
char c;
int StarNum = 0, humanproof;
cout << "Do you wanna create a user or login?";
cout << "\nLogin" << endl;
cout << "New" << endl;
cin >> lon;
if(lon=="login"){
goto login;
}
if(lon=="new"){
goto newa;
}
login:
cout << "Username: ";
cin >> username;
lol:
cout << "Password: ";
while (c != 13)
{
c = (char)getch();
if(c == 13) break;
StarNum++;
password += c;
cout << "*";
if (c == 127 || c == 8){
//go here to fix the problem
}
password = "";
goto lol;
}
}
if(username == "user" && password == "pass" || username == nu && password == np){
cout << "\nYou are logged in.";
goto options;
} else {
cout << "\nusername or password is wrong" << endl;
return 0;
}
return 0;
newa:
cout << "Username:";
cin >> nu;
cout << "password:";
cin >> np;
cout << "Type the number fourhoundred and twentie three too proof you are a human: ";
cin >> humanproof;
if(humanproof == 423){
cout << "The username is " << nu << endl;
for(int no = 0; no <= 100; no++){
cout << endl;
}
goto login;
return 0;
}
if(humanproof!=423){
cout << "wrong answer!";
return 0;
}
options:
int op;
cout << "\nwhat do you want to do?" << endl;
cout << "1. Calculator" << endl;
cout << "2. About"<< endl;
cout << "3. Just for fun" << endl;
cout << "4. Exit" << endl;
cin >> op;
if(op==1){
goto calculator;
}
if(op==2){
goto info;
}
if(op==3){
goto fun;
}
if(op==4){
return 0;
}
else{
cout << "you entered a invalid number. " << endl;
return 0;
}
calculator:
double n1, n2, sum;
int opa;
cout << "Choose a operation" << endl;
cout << "1. Addition/+" << endl;
cout << "2. Subscraction/-" << endl;
cout << "3. Multiplication/x" << endl;
cout << "4. Divsion/ /" << endl;
cin >> opa;
if(opa == 1){
cout << "enter number 1" << endl;
cin >> n1;
cout << "enter number 2" << endl;
cin >> n2;
sum = n1 + n2;
cout << "the sum is " << sum;
return 0;
}
if(opa == 2){
cout << "enter number 1" << endl;
cin >> n1;
cout << "enter number 2" << endl;
cin >> n2;
sum = n1 - n2;
cout << "the sum is " << sum;
return 0;
}
if(opa == 3){
cout << "enter number 1" << endl;
cin >> n1;
cout << "enter number 2" << endl;
cin >> n2;
sum = n1 * n2;
cout << "the sum is " << sum;
return 0;
}
if(opa == 4){
cout << "enter number 1" << endl;
cin >> n1;
cout << "enter number 2" << endl;
cin >> n2;
sum = n1 / n2;
cout << "the sum is " << sum;
return 0;
}
if(opa > 4){
cout << "You entered a invalid number";
goto calculator;
}
info:
cout << "Created by Bergur 2013";
return 0;
fun:
cout << "You want an eyepad(ipad)?";
}

Your code already checks:
while (c != 13)
And prevent newline from being handled, do similar to what you need with the backspace character, whose number is 8
To fix your issue, before:
StarNum++;
Add:
if (c == 8 && StarNum > 0) {
StarNum--;
if (password.size () > 0)
password.resize (password.size () - 1);
continue;
}

Please format your code. Also, try to provide a minimal code which reproduce the problem, not the whole code.
Unrelated to your problem
Try not to use goto.
Do not use ASCII values, but use the char literals instead, i.e. use '\n' instead of 13.
Also, you can simply add an iother condition inside your while:
while (c != '\n' && c != ' ')

Related

How to read and store a string value in c++ [duplicate]

This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Why must type getline(cin, string) twice?
(5 answers)
Closed 9 months ago.
what's wrong
if I use the get line function only once in the character modifier function the compiler will ignore it
unless I call the function twice
why cant I use it only once?
I tried using other ways, it worked but I wanna understand this one
I'm now just writing random things so the add more details error messages go away
#include <iostream>
#include<string>
using namespace std;
class egybest
{
string link,m;
char sys, type, restart;
int s = 1, e = 1, date;
public:
string charmodifier()
{
//here
getline(cin, m);
getline(cin, m);
for (int x = 0; x <= m.size(); x++)
{
if (m[x] == ' ')
m[x] = '-';
}
return m;
}
~egybest()
{
system("cls");
cout << "do you want to restart the program? y:n;" << endl;
cin >> restart;
system("cls");
if (restart == 'y' || restart == 'Y')
egybest();
else if (restart == 'n' || restart == 'N')
{
system("exit");
}
}
egybest()
{
cout << "do you want to watch a movie or a series? 1:2;" << endl;
cin >> type;
system("cls");
if (type == '1')
linkmovie();
else if (type == '2')
series();
else
cout << "wrong input!" << endl;
}
void linkmovie()
{
cout << "enter the name of the movie:" << endl;
charmodifier();
cout << "enter the release date: " << endl;
cin >> date;
link = "start https://cape.egybest.cool/movie/" + m + "-" + to_string(date);
cout << endl;
system(link.c_str());
}
void series()
{
cout << "do you want it to open links for a particular season, particular episode or all seasons? s:e:a;"
<< endl;
cin >> sys;
system("cls");
if (sys == 'S' || sys == 's')
linkseason();
else if (sys == 'A' || sys == 'a')
linkall();
else if (sys == 'E' || sys == 'e')
linkepisode();
else
cout << "wrong input!" << endl;
}
void linkall()
{
cout << "season No." << endl;
cin >> s;
cout << "episode No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
charmodifier();
for (int j = 1; j <= s; j++)
{
for (int i = 1; i <= e; i++)
{
link = "start https://cape.egybest.cool/episode/" + m + "-season-" + to_string(j) + "-ep-" + to_string(i);
system(link.c_str());
}
}
cout << endl;
}
void linkepisode()
{
cout << "season No." << endl;
cin >> s;
cout << "episode No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
charmodifier();
link = "start https://cape.egybest.cool/episode/" + m + "-season-" + to_string(s) + "-ep-" + to_string(e);
cout << endl;
system(link.c_str());
}
void linkseason()
{
cout << "season No." << endl;
cin >> s;
cout << "episodes No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
charmodifier();
for (int i = 1; i <= e; i++)
{
link = "start https://cape.egybest.cool/episode/" + m + "-season-" + to_string(s) + "-ep-" + to_string(i);
cout << endl;
system(link.c_str());
}
}
};
int main()
{
egybest egy;
return 0;
}```
The problem is that after entering an integer or a character as for example
cout << "episode No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
charmodifier();
//...
the input buffer contains the new line character '\n' that corresponds to the pressed Enter key.
So the following call of getline reads an empty string until the new line character is encountered.
In such a case before calling getline you need to remove the new line character from the input buffer like for example
#include <limits>
//...
cout << "episode No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
charmodifier();
//...

why does the getline() function does not work unless I call it twice in the function charmodifier [duplicate]

This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Why must type getline(cin, string) twice?
(5 answers)
Closed 9 months ago.
what's wrong
if I use the get line function only once in the character modifier function the compiler will ignore it
unless I call the function twice
why cant I use it only once?
I tried using other ways, it worked but I wanna understand this one
I'm now just writing random things so the add more details error messages go away
#include <iostream>
#include<string>
using namespace std;
class egybest
{
string link,m;
char sys, type, restart;
int s = 1, e = 1, date;
public:
string charmodifier()
{
//here
getline(cin, m);
getline(cin, m);
for (int x = 0; x <= m.size(); x++)
{
if (m[x] == ' ')
m[x] = '-';
}
return m;
}
~egybest()
{
system("cls");
cout << "do you want to restart the program? y:n;" << endl;
cin >> restart;
system("cls");
if (restart == 'y' || restart == 'Y')
egybest();
else if (restart == 'n' || restart == 'N')
{
system("exit");
}
}
egybest()
{
cout << "do you want to watch a movie or a series? 1:2;" << endl;
cin >> type;
system("cls");
if (type == '1')
linkmovie();
else if (type == '2')
series();
else
cout << "wrong input!" << endl;
}
void linkmovie()
{
cout << "enter the name of the movie:" << endl;
charmodifier();
cout << "enter the release date: " << endl;
cin >> date;
link = "start https://cape.egybest.cool/movie/" + m + "-" + to_string(date);
cout << endl;
system(link.c_str());
}
void series()
{
cout << "do you want it to open links for a particular season, particular episode or all seasons? s:e:a;"
<< endl;
cin >> sys;
system("cls");
if (sys == 'S' || sys == 's')
linkseason();
else if (sys == 'A' || sys == 'a')
linkall();
else if (sys == 'E' || sys == 'e')
linkepisode();
else
cout << "wrong input!" << endl;
}
void linkall()
{
cout << "season No." << endl;
cin >> s;
cout << "episode No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
charmodifier();
for (int j = 1; j <= s; j++)
{
for (int i = 1; i <= e; i++)
{
link = "start https://cape.egybest.cool/episode/" + m + "-season-" + to_string(j) + "-ep-" + to_string(i);
system(link.c_str());
}
}
cout << endl;
}
void linkepisode()
{
cout << "season No." << endl;
cin >> s;
cout << "episode No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
charmodifier();
link = "start https://cape.egybest.cool/episode/" + m + "-season-" + to_string(s) + "-ep-" + to_string(e);
cout << endl;
system(link.c_str());
}
void linkseason()
{
cout << "season No." << endl;
cin >> s;
cout << "episodes No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
charmodifier();
for (int i = 1; i <= e; i++)
{
link = "start https://cape.egybest.cool/episode/" + m + "-season-" + to_string(s) + "-ep-" + to_string(i);
cout << endl;
system(link.c_str());
}
}
};
int main()
{
egybest egy;
return 0;
}```
The problem is that after entering an integer or a character as for example
cout << "episode No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
charmodifier();
//...
the input buffer contains the new line character '\n' that corresponds to the pressed Enter key.
So the following call of getline reads an empty string until the new line character is encountered.
In such a case before calling getline you need to remove the new line character from the input buffer like for example
#include <limits>
//...
cout << "episode No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
charmodifier();
//...

Keep receiving this error main.cpp:9:91: error: no match for ‘operator<<’ (operand types are ‘std::basic_ostream’ and ‘const std::vector’

Sorry in advance if this is lengthy. the problem is within line 9. (where the 2nd cout is.) apparently, but i'm new to this so I can't identify exactly what the issue is.
#include <iostream>
#include <vector>
using namespace std;
void outputRoster(const vector<int> &jersey, const vector<int> &ratings) {
cout << "ROSTER" << endl;
for (int i =1; i < jersey.size(); ++i) {
cout << "Player " << i << " -- Jersey number: " << jersey.at(i-1) << ", Rating: " << ratings << endl;
}
cout << endl;
}
void addPlayer(vector<int> &jersey, vector<int> &ratings) {
int num;
cout << "Enter another player's jersey number: ";
cin >> num;
jersey.push_back(num);
cout << "Enter another player's ratings: ";
cin >> num;
cout << endl;
ratings.push_back(num);
}
void removePlayer(vector<int> &jersey, vector<int> &ratings) {
int num;
cout << "Enter a jersey number: ";
cin >> num;
cout << endl;
for (int i = 0; i < jersey.size(); ++i){
if (jersey.at(i)==num){
jersey.erase(jersey.begin()+i);
ratings.erase(ratings.begin()+i);
break;
}
}
}
void updatePlayerRating(const vector<int> &jersey, vector<int> &ratings){
int num;
cout << "Enter a jersey number: " << endl;
cin >> num;
for (int i = 0; i < jersey.size(); ++i){
if(jersey.at(i) == num){
cout << "Enter a new rating for player: ";
cin >> num;
cout << endl;
ratings.at(i) = num;
}
}
}
void outputPlayersAboveRating(const vector<int> &jersey, const vector<int> &ratings) {
int num;
cout << "Enter a rating: ";
cin >> num;
cout << endl;
cout << "ABOVE " << num << endl;
for (int i = 0; i < ratings.size(); ++i){
if (ratings.at(i) > num) {
cout << "Player " << i+1 << " -- Jersey number: " << jersey.at(i) << ", Rating: " << ratings.at(i);
}
}
cout << endl;
}
int main() {
vector<int> jersey;
vector<int> ratings;
for (int i = 0; i < 5; ++i) {
int num;
cout << "Enter player " << i+1 << "'s jersey number:";
cin >> num;
jersey.push_back(num);
cout << "Enter player " << i+1 << "'s ratings:";
cin >> num;
ratings.push_back(num);
cout << endl;
cout << endl;
}
outputRoster(jersey, ratings);
char inp;
while(true) {
cout << "MENU" << endl;
cout << "a - Add player" << endl;
cout << "d - Remove player" << endl;
cout << "u - Update player rating" << endl;
cout << "r - Output players above a rating" << endl;
cout << "o - Output roster" << endl;
cout << "q - Quit" << endl;
cout << "Choose an option: ";
cin >> inp;
cout << endl;
if (inp == 'a') {
addPlayer(jersey, ratings);
}
else if (inp == 'd') {
removePlayer(jersey, ratings);
}
else if (inp == 'u') {
updatePlayerRating(jersey, ratings);
}
else if (inp == 'r') {
outputPlayersAboveRating(jersey, ratings);
}
else if (inp == 'o') {
outputRoster(jersey, ratings);
}
else if (inp == 'q') {
return 0;
}
}
return 0;
}
Any and all help is appreciated also if possible, could you explain how to avoid an error like this in the future.
Thanks in advance.
You cannot print ratings directly in
cout ... << ratings ... because std::vector doesn't have an operator overload for printing. Rather, you have to print out an element inside that vector, so change it to cout ... << ratings[i] ..., which I'm assuming is your desired effect.
This is exactly what the compiler error is telling you. std::vector doesn't have an overload (no operator<< match).

Sporadic infinite loop during do-while c++

Sometimes when I run the program, it runs perfectly fine. Sometimes I get an infinite loop that just keeps displaying my first choice menu. I tried searching for the error and I couldn't figure it out. I thought there was an error in my input statement when I got the menuChoice, but I was unable to troubleshoot it out. Should I be checking the value of menuChoice more often? To better specify, I am referring to the second do-while loop, the one that reprints the menu choices after each iteration.
main.cpp
#include <vector>
#include <fstream>
#include <iostream>
#include "course.hpp"
using namespace std;
int main() {
int menuChoice, searchMenuChoice;
string fileName;
string line;
ifstream inStream;
string searchName;
string searchPrefix;
int searchNum;
vector<Course> courseList;
vector<int> enrolledClasses;
do{
cout << "Please enter the file that contains othe course data: ";
cin >> fileName;
inStream.open(fileName);
}while (!inStream.is_open());
cout << endl;
while (getline(inStream, line)){
courseList.push_back(Course(line));
}
cout << "Welcome to Banner NE, short for Never Existed!" << endl;
do {
cout << "\n"<< "---------------------------------------------" << endl;
cout << "1 - List all available classes" << endl;
cout << "2 - Search for a course" << endl;
cout << "3 - View your current enrolled courses" << endl;
cout << "4 - Enroll in course" << endl;
cout << "5 - Exit" << endl;
cout << "Make your selection here: ";
cin >> menuChoice;
cout << endl;
if (menuChoice == 5){
cout << "Thank you for using Banner NE and have a nice day!" << endl;
return 0;
}
if (menuChoice == 2) {
cout << endl;
cout << "Would you like to search by" << endl;
cout << "1 - Course number" << endl;
cout << "2 - Available seats remaining" << endl;
cout << "3 - Instructor name" << endl;
cout << "4 - Course prefix" << endl;
cout << "Make your selection: ";
cin >> searchMenuChoice;
if (searchMenuChoice == 2) {
for (int i = 0; i < courseList.size(); i++){
if (courseList.at(i).getSeatsRemaining() > 0)
courseList.at(i).printCourse();
}
}
if (searchMenuChoice == 1) {
cout << "Please enter the course number: ";
cin >> searchNum;
for (int i = 0; i < courseList.size(); i++){
if (courseList.at(i).MatchesCourseNumberSearch(searchNum))
courseList.at(i).printCourse();
break;
}
}
if (searchMenuChoice == 3) {
cout << "Please enter the name of the instructor: ";
cin >> searchName;
for (int i = 0; i < courseList.size(); i++) {
if (courseList.at(i).MatchesInstructorSearch(searchName))
courseList.at(i).printCourse();
}
}
if (searchMenuChoice == 4){
cout << "Please enter the prefix you would like to search for: ";
cin >> searchPrefix;
for (int x = 0; x < courseList.size(); x++)
if (courseList.at(x).MatchesPrefix(searchPrefix))
courseList.at(x).printCourse();
}
}
if (menuChoice == 1) {
for (int x = 0; x < courseList.size(); x++){
cout << "ID: " << x << "\t";
courseList.at(x).printCourse();
cout << endl;
}
}
if (menuChoice == 4) {
int classEnrollment;
cout << "Please enter the ID number of the class you would like to enroll: ";
cin >> classEnrollment;
if (courseList.at(classEnrollment).Enroll()){
enrolledClasses.push_back(classEnrollment);
cout << "You have enrolled in ID " << classEnrollment << endl;
}
else
cout << "There was not enough space, sorry." << endl;
}
if (menuChoice == 3){
for (int i = 0; i < enrolledClasses.size(); i++){
courseList.at(enrolledClasses.at(i)).printCourse();
cout << endl;
}
if (enrolledClasses.size() == 0 )
cout << "You are not currently enrolled in any classes." << endl;
}
} while (menuChoice != 5);
return 0;
}

Is it a good idea if I put all this in a different function?

So I'm working on this endterm project. Which the teacher said that we should use functions now. Which he recently introduced to us. My question is if it's a good idea to put every option into a function? Functions are for organizing and for code reuse right? Or I'm missing the point of functions. XD
What I mean is like making a function for option 1, which is add account. Instead of putting it in the main function. So far I only made a function for options 3,4 and 5. Which are search, view and delete functions
#include <iostream>
#include <string>
using namespace std;
bool accountSearch(int searchParameter);
void viewList();
void deleteFromList(int delParameter);
int option, numberOfAccounts = 0, accountNumSearch, index, deleteAccount;
struct personAccount
{
int currentBalance, accountNumber, pin;
string lastname, firstname, middlename;
};
personAccount account[20];
int main()
{
do{
cout << "[1] Add Account" << endl
<< "[2] Edit Account" << endl
<< "[3] Search Account" << endl
<< "[4] View Account" << endl
<< "[5] Delete Account" << endl
<< "[6] Inquire" << endl
<< "[7] Change Pin Number" << endl
<< "[8] Withdraw" << endl
<< "[9] Deposit" << endl
<< "[10] View Transactions" << endl
<< "[11] Exit" << endl << endl
<< "Option [1-11]: ";
cin >> option; cout << endl;
if(option == 1)
{
if(numberOfAccounts != 20)
{
cout << "Account Number: ";
cin >> account[numberOfAccounts].accountNumber;
cout << "PIN: ";
cin >> account[numberOfAccounts].pin;
cout << "Lastname: ";
cin >> account[numberOfAccounts].lastname;
cout << "Firstname: ";
cin >> account[numberOfAccounts].firstname;
cout << "Middlename: ";
cin >> account[numberOfAccounts].middlename;
account[numberOfAccounts].currentBalance = 0;
++numberOfAccounts;
cout << endl;
}
else
{
cout << "The list is full!\n\n";
}
}
else if(option == 2)
{
if(numberOfAccounts != 0)
{
cout << "Account Number: ";
cin >> accountNumSearch;
if(accountSearch(accountNumSearch))
{
cout << "PIN: ";
cin >> account[index].pin;
cout << "Lastname: ";
cin >> account[index].lastname;
cout << "First name: ";
cin >> account[index].firstname;
cout << "Middlename: ";
cin >> account[index].middlename;
cout << endl;
}
else
{
cout << "Account not found!\n\n";
}
}
else
{
cout << "The list is empty!\n\n";
}
}
else if(option == 3)
{
if(numberOfAccounts != 0)
{
cout << "Enter account number to search: ";
cin >> accountNumSearch;
if(accountSearch(accountNumSearch))
{
cout << "Found at index " << index << "\n\n";
}
else
{
cout << "Not found!\n\n";
}
}
else
{
cout << "The list is empty!\n\n";
}
}
else if(option == 4)
{
if(numberOfAccounts != 0)
{
viewList();
}
else
{
cout << "The list is empty!\n\n";
}
}
else if(option == 5)
{
if(numberOfAccounts != 0)
{
cout << "Account Number: ";
cin >> deleteAccount;
deleteFromList(deleteAccount);
}
}
}while(option != 11);
}
bool accountSearch(int searchParameter)
{
bool found = 0;
for(int i = 0; i < numberOfAccounts; i++)
{
index = i;
if (account[i].accountNumber == searchParameter)
{
found = 1;
break;
}
}
if(found)
{
return 1;
}
else
{
return 0;
}
}
void viewList()
{
for(int i = 0; i < numberOfAccounts; i++)
{
cout << "Account Number: " << account[i].accountNumber << endl
<< "Lastname: " << account[i].lastname << endl
<< "Firstname: " << account[i].firstname << endl
<< "Middlename: " << account[i].middlename << endl
<< "Current Balance: " << account[i].currentBalance << "\n\n";
}
}
void deleteFromList(int delParameter)
{
if(accountSearch(deleteAccount))
{
for(int i = index; i < numberOfAccounts; i++)
{
account[i] = account[i+1];
}
--numberOfAccounts;
cout << "Deleted Done\n";
}
else
{
cout << "Account not found!\n";
}
}
It's not done yet, but is there anything you would like to mention or suggest?
Yes, you should write functions separately, it's common good practice as a programmer, It will be easier for you(and others) to read, follow, and understand your code.
So, if your options do different things, they should have their own functions. (More like it would be desirable, in the end it's up to you)