In the code below I am trying to have the variable fullName be populated with whatever I enter during the operation of the function namecheck. I am not sure where I am going wrong. Please help and thank you for it.
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <cmath>
#include <string>
#include <fstream>
using namespace std;
string namecheck();
int main()
{
cout<<fixed;
string firstName;
string lastName;
string fullName;
char action;
int pin;
int pinTry =1;
int actionsTaken =0;
int joeyPin = 4433;
int mildredPin = 2849;
double joeyTotal = 3742.55;
double mildredTotal = 19.36;
double withdraw;
double deposit;
namecheck();
cout<<fullName;
}
string namecheck(){
string firstName;
string lastName;
string fullName;
string completeName;
double joeyTotal = 3742.55;
double mildredTotal = 19.36;
cout<<"Welcome to Blah National Bank!\n";
cout<<"What is your first name?\n";
cin>>firstName;
if (firstName == "END"){
cout<<"User totals: \n"
<<"Joey Stowy:\t"<<setprecision(2)<<joeyTotal<<endl<<endl
<<"Mildred Moredebt:\t"<<setprecision(2)<<mildredTotal<<endl<<endl;
}
if (firstName != "END"){
cout<<"What is your last name?\n";
cin>>lastName;
}
fullName = firstName+" "+lastName;
return fullName;
}
Change:
namecheck();
cout<<fullName;
to:
fullname = namecheck();
cout<<fullName()
.
When you call namecheck() in main, assign the result to fullName:
fullName = namecheck();
Related
I recently started learning c++ so I'm still learning. Basically I'm trying to read my text file when the string "NEW_EMPLOYEE" is found and then store every line into their respective member variables until an empty line is found in the text file to stop. The problem I'm having is how can I use getline to import each line into each variable of my class "Employee" all at once? Should I use istringstream instead?
My text file called "employee.txt"
NEW_EMPLOYEE
460713
John
Smith
64000
36
END_OF_FILE
My class Employee:
class Employee {
private: //Member variables
int ID;
string FirstName;
string LastName;
int Salary;
int Hours;
public:
Employee() {} //Default constructor
Employee(int& id, string& firstName, string& lastName, int& salary, int& hours) {
ID = id;
FirstName = firstName;
LastName = lastName;
Salary = salary
Hours = hours;
}
};
My main.cpp:
#include <iostream>
#include <fstream>
int main() {
Employee employee;
int id;
string firstName;
string lastName;
int salary;
int hours;
string line;
ifstream employeeFile;
employeeFile.open("employee.txt");
while(getline(employeeFile, line)) {
if(line == "NEW_EMPLOYEE") {
do {
//Don't know what to do here???
} while (!line.empty());
}
}
employeeFile.close();
return 0;
}
The straightforward approach would be to do something like that
while(employeeFile >> line){
if(line != "NEW_EMPLOYEE") continue;
int id,salary,hours;
string firstName, lastName;
employeeFile >> id >> firstName >> lastName >> salary >> hours;
Employee employee = Employee(id, firstName, lastName, salary, hours);
// Do what you want with employee
}
This assumes that the data are written in the file always in the same order. I also assumed that the lines contain no spaces since they're either numbers or names so I used >> operator. You can use getline instead if that's not the case.
If you always sure the data are in the same order then this should be enough. If that's not true, I'd recommend writing the object as JSON in the file, and use a JSON parser library to read the file directly into an object.
yes..straight forward approach can help you otherwise u can use simple method like ...
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <sstream>
using namespace std;
int main() {
string x[100];
int i=0;
// Employee employee;
int id;
string firstName;
string lastName;
int salary;
int hours;
string line;
string text;
ifstream employeeFile;
employeeFile.open("employee.txt");
while(!employeeFile.eof())
{
getline(employeeFile,text);
x[i++]=text;
}
// employeeFile.close();
stringstream(x[1]) >> id; //string to int
firstName = x[2];
lastName = x[3];
stringstream(x[4]) >> salary;
stringstream(x[5]) >> hours;
//cout<<id<<" "<<firstName;
}
Then you can call your method . But straight forward approach is moore perfect than this :)
I'm quite new with c++ and need some help with the following code.
#include <iostream>
using namespace std;
struct student {
string name;
int age;
float marks;
};
struct student *initiateStudent(string , int , float);
int main ( ) {
int totalStudents = 1;
string name;
int age;
float marks;
cin >> totalStudents;
student *stud[totalStudents];
for( int i = 0; i < totalStudents; i++ ) {
cin >> name >> age >> marks;
stud[i] = initiateStudent(name,age,marks);
}
cout << stud[0]->name;
return 0;
}
struct student *initiateStudent(string name, int age, float marks)
{
student *temp_student;
temp_student->name = name;
temp_student->age = age;
temp_student->marks = marks;
return temp_student;
}
I need in the function initiateStudent return a struct pointer to the pointer array stud by passing the members name, age, marks.
I know that the problem sofar is the fact that temp_student is destroyed when I return to the main file.
So my question is how it could be done by just passing the members of the struct and then return back with information to the pointer array stud.
Thank you very much.
Semi-answer To explain the bad habits:
#include <string>
#include <iostream>
#include <vector>
//using namespace std; often injects subtle bugs. Use with caution
// read more here:
// http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice
struct student
{
std::string name; // explicit namespacing reduces possibility of unwanted collisions
int age;
float marks;
//added constructor in place of initialization function.
student(std::string name, int age, float marks):name(name), age(age), marks(marks)
{
}
};
int main()
{
int totalStudents = 1;
std::string name;
int age;
float marks;
while (!(std::cin >> totalStudents)) // testing input for success
// Needed extra brackets caught by M.M
// teach me to not test even a throw-away example
{
std::cout << "must... have... good... input..." << std::endl;
cin.clear(); // clear the error and get rid of any other garbage the user may have input.
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
//student *stud[totalStudents]; illegal in C++
std::vector<student *> stud(totalStudents); // using dynamic array instead
for (int i = 0; i < totalStudents; )// i++ removed
{
if (std::cin >> name >> age >> marks) //testing input
{
stud[i] = new student(name, age, marks); // using constructor
i++; // and put here. Only increment if input is valid.
}
else
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
std::cout << stud[0]->name;
for (student * stu: stud) // cleaning up allocated memory
{
delete stu;
}
return 0;
}
One of the beauties of C++ is you rarely need to self-manage memory. In fact there are huge advantages in not doing it above and beyond not having to clean up after yourself.
#include <string>
#include <iostream>
#include <vector>
struct student
{
std::string name;
int age;
float marks;
student(std::string name, int age, float marks):name(name), age(age), marks(marks)
{
}
};
int main()
{
std::string name;
int age;
float marks;
std::vector<student> stud; // look ma! No pointer!
while (std::cin >> name >> age >> marks) //exits loop on bad input
{
stud.emplace_back(name, age, marks); // building directly in vector
// vector will size itself as needed.
}
std::cout << stud[0].name;
return 0;
}
One more caveat: >> is whiespace delimited. That means it stops when it finds whitespace (space, tab, end of line...) so a name of "John Jacob Jingleheimer-Shmidt" will go into name as "John". >> will then attempt to interpret "Jacob" as age, and that will not go so well.
the simple solution is to make your initiateStudent() creates temp_student on the heap (with new): and returns it. keep in mind heap allocated memory is not freed automatically so don't forget to free it later on yourself.
#include <iostream>
#include <string>
using namespace std;
struct student {
string name;
int age;
float marks;
};
struct student *initiateStudent(string , int , float);
int main ( ) {
int totalStudents = 1;
string name;
int age;
float marks;
cout << "Total student: ";
cin >> totalStudents;
cin.sync(); // very very important to not affect the next input (name)
student* stud = new student[totalStudents];
for( int i = 0; i < totalStudents; i++ )
{
cout << "Name: ";
getline(cin, name);
cin.sync();
cout << "age: ";
cin >> age;
cout << endl;
cout << "Marks: ";
cin >> marks;
cout << endl;
cin.sync();
stud[i] = *initiateStudent(name, age, marks);
}
cout << "Student 1: " << stud[0].name << endl;
delete[] stud;
stud = NULL;
return 0;
}
struct student *initiateStudent(string name, int age, float marks)
{
student *temp_student = new student;
temp_student->name = name;
temp_student->age = age;
temp_student->marks = marks;
return temp_student;
}
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.
My current assignment is to create a simple
Student Class that takes the
first name
last name
student ID number
from an object and outputs the name as a single string and his/her ID number. The program also has to count every student and output the total number of students. In this program I'm given 4 students.
I've created the program, given below. Everything compiles correctly and runs but my output is strange. Instead of giving me the students' ID and name, it gives me the number "-858993460". I have no idea why my program's doing this and a long search on the internet hasn't helped me much.
Student.h
#include <iostream>
#include <string>
using namespace std;
class Student
{
private:
string firstName;
string lastName;
int id;
string name;
public:
static int numberOfStudents;
Student();
Student(string theFirstName, string theLastName, int theID);
string getName();
int getID();
};
Student.cpp
#include "Student.h"
#include <iostream>
#include <string>
using namespace std;
//initialize numberOfStudents to 0
int Student::numberOfStudents = 0;
//initialize default constructor
Student::Student()
{
numberOfStudents++;
}
//initialize overloaded constructor
Student::Student(string theFirstName, string theLastName, int theID)
{
theFirstName = firstName;
theLastName = lastName;
theID = id;
numberOfStudents++;
}
//getName
string Student::getName()
{
return firstName += lastName;
}
//getID
int Student::getID()
{
return id;
}
main.cpp(this is my driver file)
#include "Student.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
Student st1("Hakan", "Haberdar", 1234), st2("Charu", "Hans", 2345), st3("Tarikul", "Islam", 5442), st4;
cout << "We created " << Student::numberOfStudents<<" student objects." << endl;
cout << st1.getID()<<" "<<st1.getName()<<endl;
cout << st2.getID()<<" "<<st2.getName()<<endl;
cout << st3.getID()<<" "<<st3.getName()<<endl;
cout << st4.getID()<<" "<<st3.getName()<<endl;
system("pause");
};
This is what my output is supposed to look like:
We created 4 student objects.
1234 Hakan Haberdar
2345 Charu Hans
5442 Tarikul Islam
0
This is what my output instead looks like:
We created 4 student objects.
-858993460
-858993460
-858993460
-858993460
I think my problem has something to do with my getName() function, but I'm not sure and I don't know what to try.
Student::Student(string theFirstName, string theLastName, int theID)
{
theFirstName = firstName;
theLastName = lastName;
theID = id;
numberOfStudents++;
}
Your assignments are the wrong way round. You're assigning the as yet uninitialised members to the arguments. Instead you should have:
Student::Student(string theFirstName, string theLastName, int theID)
{
firstName = theFirstName;
lastName = theLastName;
id = theID;
numberOfStudents++;
}
This mistake would have been avoided if you had used a member initialization list instead:
Student::Student(string theFirstName, string theLastName, int theID)
: firstName(theFirstName), lastName(theLastName), id(theID)
{
numberOfStudents++;
}
Not sure if the following is the reason for your issues, but it does seem wrong...
return firstName += lastName;
What this does is modifies firstname by appending last name to it, then returning modified string.
I think you meant to do something like
return firstName << ' ' << lastName;
Change your code to.
Student::Student(string theFirstName, string theLastName, int theID)
{
firstName = theFirstName;
lastName = theLastName;
id = theID;
numberOfStudents++;
}
Your code returning the value of id! which is not initialized.
So the code will return garbage.
I want to find a specific id from file and modify content.
Here is originol code which I want.
// test.txt
id_1
arfan
haider
id_2
saleem
haider
id_3
someone
otherone
C++ Code:
#include <iostream>
#include <fstream>
#include <string>
using namesapce std;
int main(){
istream readFile("test.txt");
string readout;
string search;
string Fname;
string Lname;
cout<<"Enter id which you want Modify";
cin>>search;
while(getline(readFile,readout)){
if(readout == search){
/*
id remain same (does not change)
But First name and Last name replace with
user Fname and Lname
*/
cout<<"Enter new First name";
cin>>Fname;
cout<<"Enter Last name";
cin>>Lname;
}
}
}
Suppose:
A user search id *id_2*. After that user enter First name and Last name Shafiq and Ahmed.
After runing this code the test.txt File must modify the record like that:
...............
...............
id_2
Shafiq
Ahmad
.................
.................
Only id_2 record change remaing file will be same.
UPDATE:
#include <iostream>
#include <string.h>
#include <fstream>
using namespace std;
int main()
{
ofstream outFile("temp.txt");
ifstream readFile("test.txt");
string readLine;
string search;
string firstName;
string lastName;
cout<<"Enter The Id :: ";
cin>>search;
while(getline(readFile,readLine))
{
if(readLine == search)
{
outFile<<readLine;
outFile<<endl;
cout<<"Enter New First Name :: ";
cin>>firstName;
cout<<"Enter New Last Name :: ";
cin>>lastName;
outFile<<firstName<<endl;
outFile<<lastName<<endl;
}else{
outFile<<readLine<<endl;
}
}
}
It also contain pervious First Name and Last Name in temp.txt file.
After finding the specific id and writing the new first name and last name, you need to skip the following two lines. This code works:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void skipLines(ifstream& stream, int nLines)
{
string dummyLine;
for(int i = 0; i < nLines; ++i)
getline(stream, dummyLine);
}
int main()
{
ofstream outFile("temp.txt");
ifstream readFile("test.txt");
string readLine;
string search;
string firstName;
string lastName;
cout<<"Enter The Id :: ";
cin>>search;
while(getline(readFile,readLine))
{
if(readLine == search)
{
outFile<<readLine;
outFile<<endl;
cout<<"Enter New First Name :: ";
cin>>firstName;
cout<<"Enter New Last Name :: ";
cin>>lastName;
outFile<<firstName<<endl;
outFile<<lastName<<endl;
skipLines(readFile, 2);
}
else
{
outFile<<readLine<<endl;
}
}
}