c++ Printing from a struct - c++

I'm working on something and the gist of what I have to do is essentially:
1) Declare a struct named partType that has two members: name (holds the name of a
part) and code (holds a whole number).
2) Declare two variables of type partType.
3) Prompt the user to enter the name and code of the first item and store them
into the corresponding variable.
4) Prompt the user to enter the name and code of the second item and store them
into the corresponding variable.
5) Compare the items by code and display an output like the one shown in the
examples below:
Example 1:
Enter name and code of item1: bolt 22222
Enter name and code of item2: nut 11111
bolt goes after nut in the inventory
Example 2:
Enter name and code of item1: bolt 11111
Enter name and code of item2: nut 22222
bolt goes before nut in the inventory
The current code that I have is:
#include <iostream>
#include <string>
using namespace std;
struct partType {
string name;
int code;
};
int main() {
partType nam, num;
cout << "enter name and code of item1: ";
cin >> nam.name >> num.code;
cout << "enter name and code for item2: ";
cin >> nam.name >> num.code;
if (num.code > num.code) {
cout << nam.name << " goes after " << nam.name;
}
else if (num.code < num.code) {
cout << nam.name << " goes before " << nam.name;
}
else {
cout << "tie";
}
system("pause");
return 0;
}
I feel that I shouldn't be using the nam and num twice because it'll overwrite it but I'm not completely sure on how to fix it

Reading your code, you seem to be mixing up your nam and num variables.
partType nam, num;
This line creates two partType variables, one called nam and the other called num.
cout << "enter name and code of item1: ";
cin >> nam.name >> num.code;
Watch out! You prompt for the name and code for the first item, but you place the input for the code into the second variable!
cout << "enter name and code for item2: ";
cin >> nam.name >> num.code;
Instead of setting both fields of the second variable, num, you are only setting the code field of the second variable, but setting the name field of the first variable, and furthermore you are overwriting the data that was inputted from the first input prompt.
if (num.code > num.code) {
cout << nam.name << " goes after " << nam.name;
}
else if (num.code < num.code) {
cout << nam.name << " goes before " << nam.name;
}
You are comparing an expression to itself. You should do num.code < nam.code and vice versa instead.

Related

How can I find in an array of objects the main actor I need

This is my task:
I have done half of my code, but I'm struggling because I'm a beginner in OOP and I'm not sure how I can find movie where main_actor is Angelina Jolie.
for (int i = 0; i < n; ++i)
{
string name;
int year;
string prod;
string actor;
cout << "\nenter the film name " ;
cin >> name;
cout << "\nenter the production year ";
cin >> year;
cout << "\nenter the producer name ";
cin >> prod;
cout << "\nenter the actor name ";
cin >> actor;
obs[i].SetName(name);
obs[i].SetYearP(year);
obs[i].SetProducer(prod);
obs[i].SetMaina(actor);
if (actor == "Angelina Jolie")
{
cout << "The movie who has main actor Angelina Jolie is" << name << endl;
} // Đ¢his is my attempt.
}
}
You need to make a function that loops over your array and checks the main-actor:
bool findFilm(Film* films, int numFilms, string actor)
{
bool found = false;
for (int i = 0; i< numFilms; i++) {
if(!actor.compare(0, films[i].GetyMaina().length(), films[i].GetyMaina()){
cout<<"Film "<<films[i].GetName()<<" has main actor "<<actor<<"\n";
found = true;
}
}
return found;
}
The first thing you should do is using C++ containers like std::vector, std::array instead of raw array. And of course, then you should fill them.
std::vector<Films> films;
std::array<Films, 100> films;
The seconds thing is, you should delete "Films() = default;" part. That declaration changes everything in C++.
After these changes, you will be able to use containers' template member functions and algorithm functions (like find(), find_if(), count() etc.) to get what you need.
#include <algorithm>
If you are not able to do these changes, simply you can do it by looping:
for(auto film : films){
//comparisons, if checks, returns
}
Please use getline() function for user input because cin >> name will save from name Angelina Jolie only Angelina. Because it is reading only whole words not including white space.
To use function getline() put this after #include<cstring>
#include <string>
So use getline like this :
cout << "\n enter the actor name ";
std::getline (std::cin,actor);
Another problem is that you need cin.ignore() between two inputs. Because you need to flush the newline character out of the buffer in between.
Before loop ask for data like this :
cout << "how many films ";
cin >> n;
cin.ignore();
In loop like this :
cout << "\n enter the film name ";
getline(cin, name);
cout << "\n enter the production year ";
cin.ignore();
cin >> year;
cout << "\n enter the producer name ";
cin.ignore();
getline(cin, prod);
cout << "\n enter the actor name ";
getline(cin, actor);
b) (put this function in your class in public section right after string GetMania() ):
static void FindFilm(Film arr[], int cntFilms, string actor)
{
for (int i = 0; i < cntFilms; i++)
{
if (arr[i].GetMaina() == "Angelina Jolie")
cout << "The movie who has main actor Angelina Jolie is" << arr[i].GetName() << endl;
}
}
And from main call it like this right after loop.
string actor = "Angelina Jolie";
Film::FindFilm(obs, n, actor);
Also it's better if you write escape sequence (or special character) for new line (\n) to the end of output message. Like this :
cout << "The name of movie: \n" << name;

User can't put input for second variable. C++

Whenever I run the program, I can only input a value for the first variable, employeeName, but when I hit enter after I input the value, I get a "press any key to continue" prompt. Can somebody please tell me what's wrong?
// Calculate how many hours an employee has worked
#include <iostream>
using namespace std;
int main()
{
//Declare Named Constants
int const HOURS_IN_WORK_WEEK = 40;
int const HOURS_IN_WORK_DAY = 8;
//Declare Variables
int employeeName;
int hoursWorked;
int totalWeeksWorked;
int leftoverFromWeeks;
int totalDaysWorked;
int leftoverFromDays;
int totalHoursWorked;
//Get Input
cout << "enter employee name: ";
cin >> employeeName;
cout << "Enter total hours worked: ";
cin >> hoursWorked;
//calculate total weeks, days, and hours worked
totalWeeksWorked = hoursWorked / HOURS_IN_WORK_WEEK;
leftoverFromWeeks = hoursWorked % HOURS_IN_WORK_WEEK;
totalDaysWorked = leftoverFromWeeks / HOURS_IN_WORK_DAY;
leftoverFromDays = leftoverFromWeeks % HOURS_IN_WORK_DAY;
totalHoursWorked = leftoverFromDays;
//Output
cout << employeeName << "worked " << hoursWorked << "hours or " << totalWeeksWorked << "week(s), " << totalDaysWorked << "day(s), and " << totalHoursWorked << "hours.";
system("pause");
}//End Main
What I presume happened is that you unknowingly entered a string for the employee's name. However, if you look at your declaration:
int employeeName;
The type of the variable is int! Change this to std::string and use getline to read a space separated full name (std::cin will stop reading at whitespace, meaning the rest of the input will be attempted to be stored in an int, leading to the same behavior that happened with the first variable).
The input code would now change to:
cout << "enter employee name: ";
getline(cin, employeeName);
Also, on a side note, you should read why using system("pause") is not a good idea (Although it doesn't really matter for such a small program, it is useful knowledge).

Console will keep closing out instead of reading the string within the if statements

What I want to do is to have the player "select" what class they want to be, and each class has a number. A different number will print out a different string into the console, and I wanted to do that through making if statements. In other words, the player will type in a choice and their choice will end up printing something from a different if statement. However, every time I run the code, the program will just end when it asks the user what class they want to use, and won't print out the message that is for that class.
#include "stdafx.h"
#include<iostream>
#include <string>
using std::cout;
using std::cin;
using std::endl;
using std::string;
int main()
{
int Name,Class;
cout << "Welcome to the world of Jumanji!\n\n";
cout << "Please Tell me your name:";
cin >> Name;
cout << "\n\nOkay, so your name is " << Name << "? Welcome to the world of Jumanji - A game for those who seek to find a way to leave their world behind\n\n";
cout << "I am a fellow adventurer who will aid you during your journey\n\n";
cout << "Alright " << Name << "I need you to tell me what you will be playing as\n\n";
cout << "1.Archaeologist\n2.Cartographer\n3.Commando\n4.Pilot\n5.Zoologist ";
cin >> Class;
if (Class == 1) {
cout << "Are you sure that you want to be a Archaeologist?";
system("pause");
}
else if (Class == 2) {
cout << "Are you sure that you want to be a Cartographer?";
system("pause");
}
else if (Class == 3) {
cout << "Are you sure that you want to be a Commando?";
system("pause");
}
else if (Class == 4) {
cout << "Are you sure that you want to be a Pilot?";
system("pause");
}
else if (Class == 5) {
cout << "Are you sure that you want to be a Zoologist?";
system("pause");
}
return 0;
}
What am I doing wrong?
so, name should be string, not int.
string Name;
int Class;
Because the user might enter "John Doe" as the name, cin >> Name; would only get the "John", and leave "Doe", in the buffer which now ends up in Class, that causes Class to contain an arbitrary value. Thus the if else doesn't work. using getline() should fix things.
string Name;
int Class;
cout << "Welcome to the world of Jumanji!\n\n";
cout << "Please Tell me your name:";
getline(cin, Name);

Strange character in C++ program output

I am creating an ATM program in C++ for school and I'm using this project as an opportunity to begin learning the language. I am trying to output bank accounts to a text file in this format:
First Last
CardNumber
PinNumber
Balance
Originally it was outputting fine and then I developed a bunch of new methods etc. I didn't change any of the original code that has to do with outputting the bank account but now it's outputting strangely.
My output ends up being:
First Last
random letter or symbol
PinNumber
blank
Here is my code for creating a new bank account:
AccountHandler.h
#include <iostream>
#include <string>
using namespace std;
struct bankAccount //Create a new bank account type
{
string name;
string cardNum;
string balance;
string pin;
};
class AccountHandler
{
public:
AccountHandler();
~AccountHandler();
void withdraw(struct bankAccount acc, string amount);
void deposit(struct bankAccount acc);
int checkBalance(struct bankAccount acc);
void createAccount();
};
AccountHandler.cpp
void AccountHandler::createAccount() //creates a new bank account and stores in accounts.txt
{
ofstream accounts;
struct bankAccount newAcc;
string first, last;
string tempPin1, tempPin2;
if (!accounts.is_open())
{
accounts.open("accounts.txt", ofstream::app);
}
std::cout << "Thank you for choosing to bank with ATM406!\n\n";
std::cout << "Please enter the name for the account: ";
std::cin >> first >> last;
newAcc.name = first + " " + last;
while (true)
{
std::cout << "\nPlease enter a 4-digit pin for security: ";
std::cin >> tempPin1;
std::cout << "\nPlease re-enter your 4-digit pin for validation: ";
std::cin >> tempPin2;
if (tempPin1 == tempPin2) //PINS MATCH
{
newAcc.pin = tempPin1;
break;
}
else //PINS DO NOT MATCH
{
std::cout << "The pins did not match!" << std::endl;
}
}
//GENERATE A RANDOM 4-DIGIT NUMBER FOR CARDNUM
srand(time(NULL));
newAcc.cardNum = rand() % 9000 + 1000;
//STORE ACCOUNT IN FORMAT: NAME\nCARDNUM\nPIN\nBALANCE
accounts << newAcc.name << "\n" << newAcc.cardNum << "\n"
<< newAcc.pin << "\n" << newAcc.balance << "\n";
accounts.close();
std::cout << "\nAccount created with name: " << newAcc.name << " pin: " << newAcc.pin
<< ". Card number: " << newAcc.cardNum << "\n\n\n";
}
Thank you!
cardNum is a string, but you assign an integer to it. That converts the integer to a char (truncating it to a much smaller value) and stores it in the string.
balance is blank because it's an empty string, you never give the string a value.
N.B. the call to is_open() in createAccount is pointless, the fstream can't be open, because you just default-constructed it.

Calling for function, only returning 0

Alrighty, the goal of what I am trying to do right now is call the function getSingleStudentInfo, which contains the student's number, last name, and age. In the end this program is designed to do two things, the first being the single student info, the second, printing out an array of 20 students. Disregard the second part, as I have not really gotten into that part yet, so ignore anything involving vectors.
The problem that I am having is that in main the first thing that the program will do is ask you to press 1 for the single info or 2 for the full 20 peoples info. The program compiles fine, but what happens is, no matter what number you enter, the program will say "process returned 0 (0x0)" and be done, I'm having a hard time figuring out why it is doing that instead of printing out the single students info, being "student's ID number is 400" "student's last name is: Simmons" "student's age is: 20"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct Student {
int studentNumber = 400;
string lastName = "Simmons";
int age = 20;
};
Student s;
int selection;
vector<int> studentNumber (20);
vector<string> lastName;
vector<int> age (20);
void getSingleStudentInfo (int studentNumber, string lastName, int age) {
cout << "Student's ID number is: ";
cout << s.studentNumber << endl;
cout << "Student's last name is: ";
cout << s.lastName << endl;
cout << "Student's age is: ";
cout << s.age << endl;
return;
};
int main()
{
cout << "Press '1' to see a single student data entry" << endl;
cout << "Press '2' to see all 20 student records" << endl;
cin >> selection;
if (selection == 1) {
getSingleStudentInfo;
};
/*for (vector<int>::size_type i = 0; i <= 20; i++)
{
cout << "Student's ID number is: " << 400 + i << endl;
}
return 0;*/
}
You need to call the function, e.g.
if (selection == 1)
{
getSingleStudentInfo(7, "Johnson", 20);
}
However, it seems like by the implementation, this should be a method off of the student itself
struct Student {
int studentNumber = 400;
string lastName = "Simmons";
int age = 20;
void getSingleStudentInfo() const;
};
Then you'd call it off a Student instance
Student s{400, "Simmons", 20};
s.getSingleStudentInfo();
Then if you had a vector of Student you could do
std::vector<Student> students; // assume this has been populated
std::for_each(begin(students),
end(students),
[](const Student& s){s.getSingleStudentInfo();});
To print in columns, you could change your function to something like
void Student::getSingleStudentInfo()
{
cout << s.studentNumber << '\t'
<< s.lastName << '\t'
<< s.age << endl;
};