Vector printing incorrect data - class

Can someone tell my why my program prints wrong values?
I've mostly followed an youtube video how to use vectors. And the program which was written, i was able to run it. I tried to implement the same method for my program which is for cars (video was for students). But i'm having problems. Funny part is, that the student program ran well, i don't remember changing anything to it, and now it also doesn't print anything at all.
So i'm trying to make a program that inputs car brand, year and price into a vector of a class and then print out all the stored information. But i'm currently getting mixed results.
I'm either getting blank spaces for results or some huge numbers and blank space for the brand (string)
When i'm not using references & i get blank results, with & i get what i've written below.
Does anyone have an idea?
When i input:
brand - Lambo
year - 1997
price 25000
I get:
Car brand:
Car year: 2686588
Car price: 6.95144e-308
main.cpp
#include <iostream>
#include <string>
#include "Car.h"
#include <vector>
using namespace std;
Car::Car(){
}
Car::Car(string brand, int year, double price){
brand;
year;
price;
}
Car::~Car(){
}
string Car::getBrand() const{
return brand;
}
int Car::getYear() const{
return year;
}
double Car::getPrice()const{
return price;
}
void Car::setBrand(string brand){
brand;
}
void Car::setYear(int year){
year;
}
void Car::setPrice(double price){
price;
}
void enterData(vector<Car>&);
void showData(const vector<Car>&);
int main(){
vector<Car> myGarage;
int chc;
cout << "-- M A I N M E N U --\n\n";
do{
cout << "Please make a choice\n\n";
cout << "1. Enter car details" << endl;
cout << "2. Show car details" << endl;
cout << "3. Exit" << endl;
cin >> chc;
switch(chc){
case 1:
enterData(myGarage);
break;
case 2:
showData(myGarage);
break;
case 3:
cout << "Have a nice day!";
break;
}
}
while(chc != 3);
}
void enterData(vector<Car>& newMyGarage){
string brand;
int year;
double price;
cout << "How many cars are in your garage?";
int garageSize;
cin >> garageSize;
for(int i = 0; i < garageSize; i++){
cout << "Car brand: ";
cin >> brand;
cout << "Car year: ";
cin >> year;
cout << "Car price: ";
cin >> price;
Car newCar(brand, year, price);
newMyGarage.push_back(newCar);
cout << endl;
}
}
void showData(const vector<Car>& newMyGarage){
unsigned int size = newMyGarage.size();
for(unsigned int s = 0; s < size; s++){
cout << "Car brand: " << newMyGarage[s].getBrand() << endl;
cout << "Car year: " << newMyGarage[s].getYear() << endl;
cout << "Car price: " << newMyGarage[s].getPrice() << endl;
cout << endl;
}
}
header file Car.h
#ifndef CAR_H_INCLUDED
#define CAR_H_INCLUDED
#include <iostream>
#include <string>
using namespace std;
class Car{
public:
string brand;
int year;
double price;
Car();
Car(string, int, double);
~Car();
string getBrand() const;
int getYear() const;
double getPrice() const;
void setBrand(string);
void setYear(int);
void setPrice(double);
};
#endif // CAR_H_INCLUDED

Related

Segmentation Error: Help on the correct allocation memory when saving & loading binary files containing a specific structure from a class

This is my first time asking a question, so apologies if it is not done 100%:
I have a class which saves and loads a binary file with a specific data structure.
If the program creates an instance of the class, save the binary file, and creates another instance of the class to load/read the binary file consequently, everything seems 100% correct.
However, if I run the program to save the binary file and then run it again to load/read that binary file, it gives me a segmentation fault at the end.
The program still does everything it needs to do before the segmentation fault, except deconstructing the class at the end (obviously).
It looks like my allocation of the memory is not correct, but I am not sure where I am going wrong.
A simplified version of the code follow (also here: https://github.com/LenteDreyer/Tests.git )
Can someone see where I am going wrong?
class header file that save/loads the file
#ifndef __TESTS_MAP_HH__
#define __TESTS_MAP_HH__
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
typedef struct test_struct{
bool test_bool;
double test_double;
std::vector<double> test_vector;
} test_struct_t;
class map
{
private:
std::string m_path, m_str;
double m_double;
test_struct m_struct;
public:
map(const std::string& a_id);
void set_str(std::string a_str);
void set_double(double a_double);
void set_struct(test_struct a_struct);
void load_file();
void save_file() const;
void show_file() const;
~map();
};
#endif //__TESTS_MAP_HH__
class source file that save/loads the binary file
#include "map.hh"
map::map(const std::string& a_id)
{
m_path = a_id + ".bin";
m_str = "none";
m_double = 0.0;
m_struct = {false, 0.0};
}
void map::set_str(std::string a_str){
m_str = a_str;
}
void map::set_double(double a_double){
m_double = a_double;
}
void map::set_struct(test_struct a_struct){
m_struct = a_struct;
}
void map::load_file(){
std::ifstream l_inF;
l_inF.open(m_path.c_str(), std::ios::binary | std::ios::in);
l_inF.read((char*)&m_double,sizeof(double));
l_inF.read((char*)&m_struct,sizeof(test_struct_t));
size_t str_size;
l_inF.read((char*)&str_size, sizeof(str_size));
m_str.resize(str_size);
l_inF.read((char*)&m_str[0], str_size);
l_inF.close();
}
void map::save_file() const{
std::ofstream l_outF;
l_outF.open(m_path.c_str(), std::ios::binary | std::ios::out);
l_outF.write((char*)&m_double,sizeof(double));
l_outF.write((char*)&m_struct,sizeof(test_struct_t));
size_t str_size = m_str.size();
l_outF.write((char*)&str_size, sizeof(str_size));
l_outF.write((char*)&m_str[0], str_size);
l_outF.close();
}
void map::show_file() const{
std::cout << ">>-----------------------------------------------" << std::endl;
std::cout << ">> double : " << m_double << std::endl;
std::cout << ">> double : " << m_double << std::endl;
std::cout << ">> struct.bool : " << m_struct.test_bool << std::endl;
std::cout << ">> struct.double : " << m_struct.test_double << std::endl;
std::cout << ">> struct.vector : " << "size = " << m_struct.test_vector.size() << std::endl;
std::cout << ">> string : " << m_str << std::endl;
std::cout << ">>-----------------------------------------------" << std::endl;
}
map::~map(){}
main function case 1 works, and case 2 gives the segmentation fault.
#include "map.hh"
int main(int argc, char const *argv[])
{
std::string id = "mapfile";
int action = 0;
if(argc > 1) action = std::stoi(argv[1]);
else {
std::string input;
std::cout << "Enter case (1 or 2): ";
std::cin >> input;
action = std::stoi(input);
}
switch (action)
{
case 1:
{
// This works 100% (no errors and it saves/reads class perfectly)
std::vector<double> l_vect = {0.1, 0.0, 0.6};
test_struct save_struct = {true, 5.0, l_vect};
map test_save(id);
test_save.show_file();
test_save.set_double(8.0);
test_save.set_str("save this string");
test_save.set_struct(save_struct);
test_save.show_file();
test_save.save_file();
map test_load(id);
test_load.load_file();
test_load.show_file();
}
break;
case 2:
{
// gives segmentation error at the end of the program
map test_load(id);
test_load.load_file();
test_load.show_file();
}
break;
default:
break;
}
return 0;
}

Accounting for space between character search

Im having issues with my code. Its been a few years since I last wrote a even a basic program. My current issue is my program is supposed to count the number of characters entered by the user and return the count of a single char also entered by the user. Where am I going wrong at? I know it has to do with the space between words. Probably a noob mistake. Thanks in advance.
#include <iostream>
#include <string>
#include<stdio.h>
#include<ctype.h>
using namespace std;
int numTimesAppear(char *mystring, char ch)//numTimes Appear function
{
int i;
int count=0;
for (i = 0; i < 100; i++)
{
if (mystring[i] == ch)
count++;
}
return count;
}
int main()
{
char str[100];
char ch;
int nooftimes;
cout << ("Enter a string of characters:") << endl;
cin >> str;
cout << ("Enter a character to count:") << endl;
cin >> ch;
cout << numTimesAppear(str, ch);
return 0;
}

Input Element Causing Errors

My class is currently studying Classes and I'm attempting to complete my assignment due tomorrow. I have most of it done, however, for some reason the address input won't let me input any letters only numbers.
I can't figure out what I'm doing wrong here and would appreciate help in figuring out if I need to change something.
#include <iostream>
using namespace std;
class personalData
{
private:
string name;
string address;
int age;
string phNumber;
public:
void setName()
{
cout << "Enter name: ";
cin >> name;
}
string getName()
{
return name;
}
void setAddress()
{
cout << "Enter address: ";
cin >> address;
}
string getAddress()
{
return address;
}
void setAge()
{
cout << "Enter age: ";
cin >> age;
}
int getAge()
{
return age;
}
void setPhone()
{
cout << "Enter phone number: ";
cin >> phNumber;
}
string getPhone()
{
return phNumber;
}
void displayData()
{
cout << "\nName: " << getName() << endl;
cout << "Address " << getAddress() << endl;
cout << "Age: " << getAge() << endl;
cout << "Phone: " << getPhone() << endl;
}
};
int main()
{
personalData person1;
personalData person3;
personalData person2;
person1.setName();
person1.setAddress();
person1.setAge();
person1.setPhone();
person1.getAddress();
cout << "\n";
person2.setName();
person2.setAddress();
person2.setAge();
person2.setPhone();
person2.getAddress();
cout << "\n";
person3.setName();
person3.setAddress();
person3.setAge();
person3.setPhone();
person3.getAddress();
cout << "\n";
cout << "Person1 details: ";
person1.displayData();
cout << "Person2 details: ";
person2.displayData();
cout << "Person3 details: ";
person3.displayData();
return 0;
}
Here is what it looks like if you input both numbers and letters:
And here is what happens if you only input numbers:

Template class method error "no 'void Pair<T1, T2>::display()' member function Pair declared in class"

I'm not sure if my syntax is incorrect. I am getting "no 'void Pair T1, T2::display()' member function Pair declared in class" as well as "no matching function for call to ‘Pair std::basic_string char, std::char_traits char" Here is the header file:
#ifndef PAIR_H
#define PAIR_H
#include <iostream>
#include <string>
using namespace std;
template <typename T1, typename T2 >
class Pair
{
private:
T1 t1;
T2 t2;
public:
Pair(const T1 & t1,const T2 & t2) : t1(t1), t2(t2) {};
T1 getFirst() const { return t1; };
T2 getSecond() const { return t2; };
//setters
void setFirst(const T1 & value) { t1 = value; };
void setSecond(const T2 & value) { t2 = value; };
};
template <typename T1, typename T2>
void Pair<T1,T2> :: display()
{
cout << t1 << " - " << t2 << endl;
}
#endif // PAIR_H
and this is the driver file.
#include <iostream>
#include <string>
using namespace std;
#include "pair.h"
int main()
{
string first;
cout << "Please enter a first name: ";
cin >> first;
string last;
cout << "Please enter a last name: ";
cin >> last;
Pair<string, string> fullName;
fullName.setFirst(first);
fullName.setSecond(last);
cout << "The first name is: " << fullName.getFirst() << endl;
cout << "The last name is: " << fullName.getSecond() << endl;
cout << "The complete pair is: ";
fullName.display();
cout << endl << endl;
int num1;
cout << "Please enter a number: ";
cin >> num1;
int num2;
cout << "Please enter another number: ";
cin >> num2;
Pair<int, int> numbers;
numbers.setFirst(num1);
numbers.setSecond(num2);
cout << "The first number is: " << numbers.getFirst() << endl;
cout << "The second number is: " << numbers.getSecond() << endl;
cout << "The complete pair is: ";
numbers.display();
cout << endl << endl;
string name;
cout << "Please enter a name: ";
cin >> name;
int score;
cout << "Please enter a score: ";
cin >> score;
Pair<string, int> grade;
grade.setFirst(name);
grade.setSecond(score);
cout << "The name is: " << grade.getFirst() << endl;
cout << "The score is: " << grade.getSecond() << endl;
cout << "The complete pair is: ";
grade.display();
cout << endl << endl;
return 0;
}
Yes, your syntax is incorrect.
1) display() is a member of Pair, so you must declare it inside the class.
You can add this declaration line in the public section
void display ();
or you can define display() inside the class (deleting the definition outside) [I added the const modifier]
void display () const { cout << t1 << " - " << t2 << endl; }
1 bis)
I suggest you to define the operator<< (output operator) for class Pair; something like, inside public, this
friend ostream & operator<< (ostream & os, Pair const & p)
{ return os << '(' << p.t1 << ',' << p.t2 << ')'; }
so you can simply output a pair like this
cout << fullName << endl;
2) You don't define a default constructor (without arguments), so you should define you pairs in this way
Pair<string, string> fullName("", "");
Pair<int, int> numbers(0, 0);
Pair<string, int> grade("", 0);
or, avoiding the following setFirst() and setSecond()
Pair<string, string> fullName(first , last);
Pair<int, int> numbers(num1, num2);
Pair<string, int> grade(name, score);
3) I don't know if you know it but there is a standard std::pair class (#include <utility>).
4) You should use che c++ tag for a question like this
5) Sorry for my bad English

C++ Why doesn't my constructor work?

I'm using visual c++ 2010 and I'm having trouble with class constructors. I've written it exactly as my instructor described and I can't seem to figure out why it wont compile.
#include <iostream>;
using namespace std;
class Account
{
public:
Insert other functions here...
Account(float b)
{
Balance = b;
}
private:
float &Balance;
}
Int main()
{
float withdraw,deposit;
Account myAccount(100.00);
cout << "Enter the amount you would like to withdraw:" << endl;
cin >> withdraw;
MyAccount.debt(withdraw);
cout << "Your balance is now "<< endl;
MyAccount.showAccountInfo();
cout << endl;
cout << "Enter the amount you would like to deposit: " << endl;
cin >> deposit;
myAccount.credit(deposit);
cout << "Your balance now is " << endl;
MyAccount.showAccountInfo();
cout << endl;
return 0;
}
It is possible that you have declared the member Balance as a reference and you are calling the constructor with a constant (i.e. 100.00), you must pass a variable name to the contructor or declare the member without the reference operator.
If you need the balance in different parts of the process you could try it with dynamic memory.
For instance:
class Account
{
public:
Insert other functions here...
Account(float* b)
{
Balance = b;
}
private:
float* Balance;
}
Int main()
{
float withdraw,deposit;
Account myAccount(new float(100.0));
cout << "Enter the amount you would like to withdraw:" << endl;
cin >> withdraw;
MyAccount.debt(withdraw);
cout << "Your balance is now "<< endl;
MyAccount.showAccountInfo();
cout << endl;
cout << "Enter the amount you would like to deposit: " << endl;
cin >> deposit;
myAccount.credit(deposit);
cout << "Your balance now is " << endl;
MyAccount.showAccountInfo();
cout << endl;
return 0;
In the updating balance method, you should unreference the pointer:
For instance...
void debt(float withdraw){
*balance -= withdraw;
}
Thanks, Regards.