User can't put input for second variable. C++ - 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).

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;

c++ Printing from a struct

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.

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.

How to use a pointer to an array of strings?

My homework problem is to modify code written for a previous assignment that saved an array (of user-specified size) of test scores so that it also saves a parallel array of student names associated with these test scores. We are to use pointers and pointer notation whenever possible.
My problem occurs early on: I ask for the student's full name and receive the input using the getline cin object and cin.ignore() to avoid passing the last name into my next cout/cin request.
However, when I attempt to recall the student name using either pointer notation (deref the pointer) or array notation all I get is blank space. String objects have been the most difficult for me to grasp this quarter, so it is possible that it is just that I am missing a crucial bit of reasoning here. I have gone back and read through my text but it is not incredibly helpful as it shows my exact format for a similar desired result. Also, most online research has been yielding info that is well beyond a first quarter c++ student like myself. Any help is very much appreciated! Here is the snippet of code where I think my problem lies:
#include<iostream>
#include<cmath>
#include<iomanip>
#include<string>
using namespace std;
void sortArray(int*, string*, int);
void averageScore(int*, int);
int main()
{
//pointer to point to test scores
int* scores;
string* student;
// integer test to indicate size of array
int test;
// get user defined array size
cout << "How many tests would you like to save?" << endl;
cin >> test;
// define dynamically allocated array scores
scores = new int[test];
student = new string[test];
// for loop to enter each test score as an element of scores array
for (int i = 0; i < test; i++)
{
cout << "Enter the student's name: " << endl;
getline(cin, student[i]);
cin.ignore();
cout << "Enter the test score for " << *(student+i) << " : "<< endl;
cin >> *(scores+i);
EDIT:
I played around with it and was able to get the results I wanted with the following code:
for (int i = 0; i < test; i++)
{
cout << "Enter the student's first name: " << endl;
cin >> first;
cout << "Enter the student's last name: " <<endl;
cin >> last;
*(student+i) = first + " " + last;
cout << "Enter the test score for " << *(student+i) << " : "<< endl;
cin >> *(scores+i);

I'm having trouble writing a console application to create a simple program to solve a math equation for superannuation

Could some one help me with this?
I've racked my head over an hour and I can't get it to work.
This is in C++ and I've been learning for a little bit but I'm still new...
int main()
{
double rate, amount,time, S;
cout << "Insert the time of the super: ";
cin >> time;
cout << "Insert the rate (as a decimal, eg 1% AKA 101% = 1.01): ";
cin >> rate;
cout << "Insert the amount $: ";
cin >> amount;
S =("amount * (rate ^ time - 1)", pow(rate,time));
cin >> S;
cout << "The total amount is: " << "S /(rate - 1)" << endl;
system("PAUSE");
return 0;
}
i dont get a compile error but i can never get an answer from it
You "never get a result" because you're setting S to the result of pow with comma operator weirdness then assigning to it again with the line
cin >> S;
which is waiting for you to input another number.
You have two main problems. Here is the updated code with comments on the altered parts:
int main()
{
double rate, amount,time, S;
cout << "Insert the time of the super: ";
cin >> time;
cout << "Insert the rate (as a decimal, eg 1% AKA 101% = 1.01): ";
cin >> rate;
cout << "Insert the amount $: ";
cin >> amount;
S = amount * pow(rate, time - 1); // take away the quotes and don't make pow seperate
cout << "The total amount is: " << (S /(rate - 1)) << endl; // do the calculation and output it
system("PAUSE");
return 0;
}
Remember that things inside quotes "like this" are string literals, so "4 * 4" is a string but 4 * 4 (see the absence of quotes) does multiplication which yields the number 16.
I don't think you should assign values to S the way you are doing it. S is declared as double and you are assinging a string to it initially. And when you output the result you are also enclosing the calculation in quotes. You should simply cout << S / (rate-1); // without quotes or cout will simply output the string