What is wrong with this code? I'm new to c++! - c++

#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
class UserBase{
public:
void GetUsername(string GetName){
MyUserName = GetName;
}
void GetPassword(string GetPassword){
GetPassword = MyPassword;
}
private:
string MyUserName;
string MyPassword;
};
int main(){
UserBase Input;
string MyName;
string MyPassword;
Input.GetUsername("test");
Input.GetPassword("noob");
cout << "enter your username, please." << endl;
cin >> MyName;
if (MyName == Input.GetUsername){
cout << "enter your password.." << endl;
cin >> MyPassword;
if (MyPassword == Input.GetPassword){
cout << "login was successfull" << endl;
Sleep(5000);
}
}
return 0; // if 0 then its a success
}
//so basically im trying to make a username and login password application. i am new to c++, i have only coded for 3 weeks and im just toying around. whenever i try to run it says that there were erros, but it didnt show me where and no red whatsoever.i use vs 2013.

here, I corrected it. Lot's of mistakes.
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
class UserBase{
public:
string GetUsername(){
return MyUserName;
}
string GetPassword(){
return MyPassword;
}
void setUsername(string name){
MyUserName = name;
}
void setPassword(string password){
MyPassword = password;
}
private:
string MyUserName;
string MyPassword;
};
int main(){
UserBase Input;
string MyName;
string MyPassword;
Input.setUsername("test");
Input.setPassword("noob");
cout << "enter your username, please." << endl;
cin >> MyName;
if (MyName == Input.GetUsername()){
cout << "enter your password.." << endl;
cin >> MyPassword;
if (MyPassword == Input.GetPassword()){
cout << "login was successfull" << endl;
Sleep(5000);
}
}
return 0; // if 0 then its a success
}
you had no real getPassword, getUsername, you only had setters (wich are called get... wich is confusing !!). You also called "getPassword" (in wrong context) with wrong syntax.
getPassword; //wrong
getPassword(); //correct

You have
if (MyName == Input.GetUsername)
But GetUsername is not a valid method call firstly, and anyways, GetUsername() returns void, where you're expecting to compare to a string MyName. Also, because the two strings within the class are private access, you don't have a way of accessing them at all outside of the class, in your main function. If you added a getter method like string getUsername() const which returned the correct string inside, then you could compare to this.

Related

New int by user input

I have a problem. I want to create an integer by user input. For example:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int i = 0;
char newVar;
string newVarName;
cout << "New Variable? (y/n)" << endl;
cin >> newVar;
if (newVar == 'y') {
/* newVarName declares new int with the name
of the user input (newVarName = test --> int test)*/
} else {
break;
}
return 0;
}
How can I do this?
As #Fantastic Mr Fox mentioned :
int name_dependant_on_user_input = value_from_user
This is impossible in c++, because the variable name, is a compile
time thing. The user input happens at runtime, which is after
compilation has completed. Something you could do, is map a string
input to your user input, for eg.
Some other error: String should be string or std::string. And using break; while not within loop or switch statements will return an error. If you want to escape immidiately, you could use exit(0);
Otherwise, as #Eljay mentioned above, a map<string, int> can be used to store both the name and value of your variable:
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
char newVar;
string newVarName;
map<string, int> varName;
cout << "New Variable? (y/n) : ";
cin >> newVar;
if (newVar == 'y') {
cout << "Name : "; cin >> newVarName;
cout << "Int : "; cin >> varName[newVarName];
} else {
exit(0);
}
//testing
cout << "Test : " << newVarName << " = " << varName[newVarName];
return 0;
}
Result:
New Variable? (y/n) : y
Name : var
Int : 5
Test : var = 5
Also, see why using namespace std; is considered a bad practice.
More info:
std::map : https://en.cppreference.com/w/cpp/container/map
std::string: https://en.cppreference.com/w/cpp/string/basic_string
In c++, you need to be aware of the common concepts of compile time and run time. So in your example:
// newVarName declares new int with the name of the user input
If you mean something like this:
int name_dependant_on_user_input = value_from_user
This is impossible in c++, because the variable name, is a compile time thing. The user input happens at runtime, which is after compilation has completed. Something you could do, is map a string input to your user input, for eg.
std::unordered_map<std::string, int> user_vars;
std::string variable_name;
int variable_value;
cin >> variable_name;
cin >> variable_value;
user_vars[variable_name] = variable_value;
...
for (const auto& value_pair : user_Vars) {
std::cout << "User value for " << value_pair.first << " is " << value_pair.second;
}

Is it possible to put multiple names in one string?

I just started learning C++ and I'm currently following a tutorial on YouTube.
I thought it was fun to make a very simple 'access' program. If I type in my name it says, "Welcome!" If I type in another name it says, "access denied". It worked perfectly fine, but then I wanted the program to say "Welcome!" to two different names. So, I wanted to add a second name in the string, but I couldn't figure out how to do that. I googled a lot but I couldn't find anything. In the end, I came to string name = ("Joe", "Sean");, but here, it was only valid for Sean. I just can't figure out how to put multiple names in one string and make them both work. I hope you can help me, here is my code:
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main()
{
string name = ("Joe", "Sean");
string input;
cout << "What is your name?\nMy name is: ";
cin >> input;
if(input == name){
cout << "Welcome, "<< input <<"! ";
} else {
cout << "Access denied";
}
return 0;
}
This is a way to do it using a vector of strings, so you can adapt easily with more names :
#include <iostream>
#include <vector>
using namespace std;
void printMessage(string message)
{
std::cout << message << std::endl;
}
int main()
{
vector<string> names{"Joe", "Sean", "Paul"};
string input;
cout << "What is your name? " << endl;
cin >> input;
for (string name : names)
{
if (name == input)
{
printMessage("Welcome!");
return 0;
}
}
printMessage("Access Denied!");
return 0;
}
The problem is in the string variable "name". You need an array of strings, not a single string.
This is an example implementation:
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main()
{
string names[] = {"Joe", "Sean"};
string input;
cout << "What is your name?\nMy name is: ";
cin >> input;
for (int i = 0; i < end(names) - begin(names); i++) {
if(input == names[i]){
cout << "Welcome, "<< input <<"! " << endl;
return 0;
}
}
cout << "Access denied" << endl;
return 0;
}
You encountered some quirky features of C++ in the approach you are using to initialize your string variable:
string s1 = ("Joe"); // creates a string "Joe"
string s2 = ("Joe", "Sean"); // creates 2 strings, "Joe" and "Sean", and the variable s2 stores only the latter!
For more details on the different methods for initializing variables there has been an interesting discussion in this previous question.

Having the following error when trying to implement a method of class using list in C++!

Edit 1
Initial idea:
MAIN.CPP:
#include <cstdlib>
#include "Cars.h"
#include "Dealer.h"
#include "Manufacturer.h"
#include <fstream>
#include <iostream>
#include <string>
#include <iostream>
#include <iomanip>
#include <list>
using namespace std;
//Instance variables for each class
string VIN = " ";
int miles;
string dealer = " ";
int price;
string vinCode=" ";
string manuCode = " ";
string manuName = " ";
string dealerName = " ";
int zipcode;
string dealerPhone = " ";
int main(int argc, char** argv) {
char command;
//Cars vehicule;
Manufacturer maker;
Dealer dealership;
ifstream infile;
ofstream outfile;
list <Cars> carsList;
//Checks if the data file exists
infile.open("database.txt", ifstream::in);
outfile.open("database.txt", ios_base::app);
//each command is a different program option
cout << "Enter a command:" << endl;
cin >> command;
while (command!='q')
{
switch (command)
{
case 'a':
{
cin >> command;
//adds a car
if (command=='c')
{
//creates a new car object and calls constructor
Cars *vehicule = new Cars();
//gets user input a assign then to variables
//for the method calls
cin >> VIN >> miles >> dealer >> price;
// 1. this is were the compiler complains
vehicule.->addData(VIN, miles, dealer, price);
vehicule.addToBase(outfile);
carsList.push_back(vehicule);
list<Cars*>::iterator it;
for(it=carsList.begin(); it!=carsList.end(); it++)
{
cout << *it->getVIN() << endl; // compile error
}
}
break;
}
//new command to keep the while loop going
cout << "Enter a command:" << endl;
cin >> command;
}
}
outfile.close();
return 0;
}
CARS.H:
#ifndef CARS_H
#define CARS_H
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
//Object that contains all information about cars (this is the class documentation)
class Cars {
public:
//class methods
*Cars(){VIN=" "; mileage=0; dealership=" "; price=0;}
void addData(string, int, string, int);
void addToBase(ofstream&);
string getVin(){return this->VIN;}
int getMiles(){return this->mileage;}
string getDealer(){return this->dealership;}
int getPrice(){return this->price;}
//private variables containing object information
private:
string VIN;
int mileage;
string dealership;
int price;
string vinCode;
};
void Cars::addData(string identification, int mile, string dealer, int money)
{
VIN=identification;
mileage=mile;
dealership=dealer;
price=money;
vinCode = VIN.substr(0,3);
return;
}
void Cars::addToBase(ofstream& file)
{
file << "c" << endl << VIN << endl << mileage << endl <<
dealership << endl << price << endl;
return;
}
Edit 2
New version of what I have gotten so far:
#include "Car.h"
#include "Dealer.h"
#include "Manufacturer.h"
#include <fstream>
#include <iostream>
#include <string>
#include <iostream>
#include <iomanip>
#include <list>
using namespace std;
string VIN;
int miles;
string dealer;
int price;
string vinCode;
string manuCode;
string manuName;
string dealerName;
int zipcode;
string dealerPhone;
int main(int argc, char** argv) {
char command;
ifstream infile;
ofstream outfile;
list<Car*> carsList;
//Checks if the data file exists
infile.open("database.txt", ifstream::in);
outfile.open("database.txt", ios_base::app);
//Reads in user input
cout << "Enter a command:" << endl;
cin >> command;
while (command != 'q')
{
switch (command)
{
case 'a': //Add
{
cin >> command;
if (command == 'c') //Add car
{
cin >> VIN >> miles >> dealer >> price;
Car* vehicule = new Car(VIN, miles, dealer, price); //New pointer
vehicule->addToBase(outfile);
carsList.push_back(vehicule);
list<Car*>::const_iterator iterator;
for (std::list<Car*>::const_iterator iterator = carsList.begin(),
end = carsList.end(); iterator != end; ++iterator)
{
cout << (*iterator)->getVin();
}
//end of for loop
}//end of if loop
}//end of case loop
break;
}//end of switch loop
cout << "Enter a command:" << endl;
cin >> command;
}//end of while loop
infile.close();
outfile.close();
return 0;
}
I still get an error:
"/Applications/Xcode.app/Contents/Developer/usr/bin/make" -f nbproject/Makefile-Debug.mk QMAKE= SUBPROJECTS= .build-conf "/Applications/Xcode.app/Contents/Developer/usr/bin/make" -f nbproject/Makefile-Debug.mk dist/Debug/GNU-MacOSX/project_1 make[2]:
*** No rule to make target `newcppsimpletest.cpp', needed by `build/Debug/GNU-MacOSX/newcppsimpletest.o'. Stop. make[1]: *** [.build-conf] Error 2 make: *** [.build-impl] Error 2
Car.h:
#ifndef CARS_H
#define CARS_H
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
class Car {
public:
Car();
Car(string, int, string, int);
void addToBase(ofstream&);
string getVin(){return this->VIN;}
int getMiles(){return this->mileage;}
string getDealer(){return this->dealership;}
int getPrice(){return this->price;}
string getVinCode(){return this->vinCode;}
private:
string VIN;
int mileage;
string dealership;
int price;
string vinCode;
};
Car::Car()
{
string VIN;
int mileage=0;
string dealership;
int price=0;
string vinCode;
}
Car::Car(string vin, int miles, string carDealer, int dollars)
{
string VIN=vin;
int mileage=miles;
string dealership=carDealer;
int price=dollars;
string vinCode = VIN.substr(0,3);
}
void Car::addToBase(ofstream& file)
{
file << "c" << endl << VIN << endl << mileage << endl <<
dealership << endl << price << endl;
return;
}
Use
vehicule->addData(VIN, miles, dealer, price);
Instead of
vehicule.->addData(VIN, miles, dealer, price);
You've declared vehicule as a pointer, but you're attempting to access methods with the '.' operator. You need to use '->' when working with pointers. Like: vehicule->addData(VIN, miles, dealer, price);
You'll need to update any code that references vehicule.
OK, I saw these two issues. You have declared vehicule as a pointer and allocated some memory like this.
Cars *vehicule = new Cars();
Then you're calling vehicule like this:
vehicule.->addData(VIN, miles, dealer, price);
vehicule.addToBase(outfile);
Strike the above.
The calls should be:
vehicule->addData(VIN, miles, dealer, price);
vehicule->addToBase(outfile);
While this seems like a small piece of code, it is always advised that, once you're done allocating, you should deallocate the memory.
Since, you add vehicule in the list, carsList, after the work is completed, do clean up the list.
You can do that, like this:
carsList.clear();
Hope this helps, You sound like you're new to this. So, trying to be as detailed as possible.

using code blocks for c++ I'm trying to print out an accessor function from my class. the error states that request for member get_address

This is my code it includes the main, header and source file I'm trying to print out an accessor function from my class AddressSpace, but its saying that
request for member "get_address" in "ob", which is of non-class type AddressSpace(std::string, std::string, std::string, int) {aka AddressSpace(std::basic_string, std::basic_string, std::basic_string, int)}
main.cpp
#include <iostream>
#include <string>
#include "AddressSpace.h"
#include "AddressSpace.cpp"
using namespace std;
int main()
{
string address;
string town;
string state;
int postal;
cout << "What is the street you live on?: " <<endl;
cin >> address;
cout << "What is the city you live in?: " <<endl;
cin >> town;
cout <<"What is the state you live in?: " << endl;
cin >> state;
cout << "What is the postal code?: " << endl;
cin >> postal;
AddressSpace ob(string address,string town,string state,int postal);
cout << "Address" << ob.get_address() << endl;
return 0;
}
AddressSpace.h
#ifndef ADDRESSSPACE_H_INCLUDED
#define ADDRESSSPACE_H_INCLUDED
#include <iostream>
#include <string>
using namespace std;
class AddressSpace{
public:
//Default constructor
AddressSpace();
//overload constructor
AddressSpace(string, string, string, int);
//Accessor Functions
string get_address() const;
// get_address - returns address
string get_town() const;
// get_town -returns town
string get_state() const;
// get_state - returns state
int get_postal() const;
// get_postal returns zip code
private:
//member variables
string street;
string city;
string st;
int zip;
};
#endif // ADDRESSSPACE_H_INCLUDED
AddressSpace.cpp
#include "AddressSpace.h"
AddressSpace::AddressSpace(string address, string town, string state, int postal){
string street = address;
string city = town;
string st = state;
int zip = postal;
}
string AddressSpace::get_address() const {
return street;
}
string AddressSpace::get_town() const {
return city;
}
string AddressSpace::get_state() const {
return st;
}
int AddressSpace::get_postal() const {
return zip;
}
The following line of code in main() is a function declaration or prototype.
AddressSpace ob(string address,string town,string state,int postal);
If you remove the type names inside the parentheses it will do what you intended, to construct an object named ob using the given parameters.
AddressSpace ob(address, town, state, postal);
When declaring a new object you don't prefix it with the type. You also haven't instantiated the strings or integer. In C/C++ un-instantiated values are random, so it's good practice to give every variable a default value. You should also include the code for AddressSpace.h and AddressSpace.cpp so we have a better idea of what else could be going wrong
Also, notice the change to the parameters of main(). It's not necessary, but considered good form to always include it. These arguments are filled in with the number of arguments and the arguments themselves if your program is run from the command line.
Your code should look more like this I think:
#include <iostream>
#include <string>
#include "AddressSpace.h"
//#include "AddressSpace.cpp" //This line isn't needed, you should only include the header file
using namespace std;
int main(int argc, char** argv)
{
string address = "";
string town = "";
string state = "";
int postal = 0; //Note postal codes for Europe include letters, and you most-likely won't be doing math with a zipcode so it might make more sense to make it a string
cout << "What is the street you live on?:" << endl;
cin >> address;
cout << "What is the city you live in?:" << endl;
cin >> town;
cout << "What is the state you live in?:" << endl;
cin >> state;
cout << "What is the postal code?:" << endl;
cin >> postal;
AddressSpace ob(address, town, state, postal);
cout << "Address " << ob.get_address(); << endl;
return 0;
}

Binary File issues

Hey guys i'm working on this simple bank account program with binary files.
For some odd reason, i can't read from the file. Or to be more on point the program crashes whenever i try to read from the file.
Can someone point me in the right direction? Thank you.
Main.cpp
#include <iostream>
#include<fstream>
#include<cstdlib>
#include "Account_Querry.h"
using namespace std;
int main()
{
Account_Querry Account;
int choice;
cout<<"***Acount Information System***"<<endl;
while(true)
{
cout<<"Select one option below ";
cout<<"\n\t1-->Add record to file";
cout<<"\n\t2-->Show All records in file";
cout<<"\n\t3-->Search Record from file";
cout<<"\n\t4-->Update Record";
cout<<"\n\t5-->Delete Record";
cout<<"\n\t6-->Quit";
cout<<"\nEnter your choice: ";
cin>>choice;
switch(choice)
{
case 1:
Account.write_rec();
break;
case 2:
//Account.search_rec();
break;
case 3:
Account.read_rec();
break;
case 4:
//Account.edit_rec();
break;
case 5:
// Account.delete_rec();
break;
case 6:
exit(0);
break;
default:
cout<<"\nEnter corret choice" << endl;
}
}
system("pause");
return 0;
}
Account_Querry.h
#ifndef ACCOUNT_QUERRY_H
#define ACCOUNT_QUERRY_H
#include <string>
#include <fstream>
class Account_Querry
{
private:
int accountNo;
std::string firstName;
std::string lastName;
double balance;
public:
void setAccountNo(int accountNo);
int getAccountNo();
void setFirstName(std::string firstName);
std::string getFirstName();
void setLastName(std::string lastName);
std::string getLastName();
void setBalance(double balance);
double getBalance();
void read_data();
void show_data();
void write_rec();
void read_rec();
void search_rec();
void edit_rec();
void delete_rec();
};
#endif // ACCOUNT_QUERRY_H
Account_Querry.cpp
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <iomanip>
#include <math.h>
#include "Account_Querry.h"
using namespace std;
void Account_Querry::setAccountNo(int accountNo)
{
this->accountNo = accountNo;
}
int Account_Querry::getAccountNo()
{
return accountNo;
}
void Account_Querry::setFirstName(string firstName)
{
this->firstName = firstName;
}
string Account_Querry::getFirstName()
{
return firstName;
}
void Account_Querry::setLastName(string lastName)
{
this->lastName = lastName;
}
string Account_Querry::getLastName()
{
return lastName;
}
void Account_Querry::setBalance(double balance)
{
this->balance = balance;
}
double Account_Querry::getBalance()
{
return balance;
}
void Account_Querry::show_data()
{
cout << "Current Information:" << endl;
cout << "-------------------------------------------------" << endl;
cout << "Name: " << firstName << ' ' << lastName << endl;
cout << "Balance: " << balance << endl;
cout << "ID#: " << accountNo << endl;
cout << "-------------------------------------------------" << endl;
cout << endl;
}
void Account_Querry::read_data()
{
cout<<"\nEnter Account Number: ";
cin>>accountNo;
cin.ignore();
cout<<"Enter First Name: ";
getline(cin,firstName,'\n');
cout<<"Enter Last Name: ";
getline(cin,lastName,'\n');
cout<<"Enter Balance: ";
cin>>balance;
}
void Account_Querry::write_rec()
{
ofstream outfile("record.bank", ofstream::app);
read_data();
outfile.write(reinterpret_cast<char *>(this), sizeof(*this));
outfile.close();
system("cls");
}
void Account_Querry::read_rec()
{
ifstream infile;
infile.open("record.bank", ios::binary);
if(!infile)
{
cout<<"Error in Opening! File Not Found!!"<<endl;
return;
}
cout<<"\n****Data from file****"<<endl;
while(!infile.eof())
{
if(infile.read(reinterpret_cast<char*>(this), sizeof(*this))>0)
{
show_data();
}
}
infile.close();
}
First of all, thanks for posting the whole code.
I just created an empty Visual Studio project in Windows and created the 3 files and copied the code you had posted in your question.
The code seems to execute perfectly fine, although while executing, the Option 2 doesn't show all the records in the file. Option 3 does show all the records in the file. You could update the Options section for that.
Apart from that, I compiled to create 32 bit binaries and 64 bit binaries and both of them seemed to work fine. Option 1 is adding new records and Option 3 is printing all the records. If I try to execute Option 3(show all records) before adding even a single record (delete the bank.record file), it is printing error message as well.
Can you tell how you are compiling the code (VisualStudio/gcc/..) on which OS (Windows/Ubuntu/..)?
Also what inputs are you giving while executing. Are you entering any non-ASCII character names like some Japanese characters?
One suggestion is: Not to dump a class object into a binary file (as done in write_rec). Better create a structure with fixed size variables (not using any string/vector).
For example, instead of string use character array, also instead of vector use static array etc. This will avoid a lot of read back issues.
Hope this helps to resolve your issue.