To give background on my code. I'm supposed to take the user input, find the month and day they input in the txt file and print that out which sound sooo simple to me but I just can't get my code to work. I want to take that I created and put it in the main so I can print whatever I have cout in that void code. I wanted some guidance to see where exactly I'm going wrong.
int main() {
cout << "please enter month first and then day: ";
cin >> searchMonth;
cin >> searchDay;
if (searchMonth == month && searchDay == day){
for (int i=0; i<TOTALDATA; i++){
infile >> year >> month >> day >> hour >> minute >> latitude >> longitude >> magnitude >> state;
earthquakeData oneEarthquake;
oneEarthquake.yearOfEarthquake = year;
oneEarthquake.monthOfEarthQuake = month;
oneEarthquake.dayOfEarthquake = day;
oneEarthquake.hourOfEarthquake = hour;
oneEarthquake.minOfEarthquake = minute;
oneEarthquake.yearOfEarthquake = latitude;
oneEarthquake.earthquakeLatitude = longitude;
oneEarthquake.earthquakeMagnitude = magnitude;
oneEarthquake.earthquakeState = state;
earthquakes[i] = oneEarthquake;// row i is set to oneEarthquake
earthquakeDetails (earthquakes[i]) ;
}
}
infile.close();
return 0;
}
void earthquakeDetails (earthquakeData earthquakes[TOTALDATA]){
for (int i=0; i<TOTALDATA; i++){
cout << earthquakes[i].yearOfEarthquake;
cout << earthquakes[i].monthOfEarthQuake;
cout << earthquakes[i].dayOfEarthquake;
cout << earthquakes[i].hourOfEarthquake << ":" << earthquakes[i].minOfEarthquake;
cout << earthquakes[i].earthquakeLatitude << earthquakes[i].earthquakeLongitude;
cout << earthquakes[i].earthquakeMagnitude;
cout << earthquakes[i].earthquakeState;
}
}```
Things you are doing wrong:
read from user without checking the input
read from file before opening a file (or your MRE is incomplete)
if outside of loop
if before reading from file
calling looping output function from looping search function
Related
my code runs without errors or anything but after I put in an "F" or "P" it skips to "click any button to continue" but if I use any numbers it goes through the code fine.
Here is my code:
#include <iostream>
#include <iomanip> // needed to use set precision
using namespace std;
void calcCost(double f_benefits, double F, double total_cost, double emp_salary)
{
if (f_benefits == F)
(total_cost += emp_salary * 1.5);
else
(total_cost += emp_salary * 1.25); // calculating operating function
}
int main()
{
double num_emp = 0; // employees
double emp_salary = 0; // employees salary
double f_benefits = 0; // are they full time or part time benifits
double total_cost = 0;
int F = 0;
int P = 0;
cout << setw(69) << "Cost of Operation\n\n";
cout << "Please enter the number of employees to process: ";
cin >> num_emp;
cout << endl;
for (int i = 1; i <= num_emp; i++) // loop for each employees salary and benifits
{
cout << "Please enter the salary for employee " << i << ":";
cin >> emp_salary;
cout << "Is employee " << i << " receiving(F)ull or (P)artial benefits ? Please enter F or P : "; // Dont forget input validation for this step
cin >> f_benefits;
}
return 0;
}
Shouldn't f_benefits be a string?
The "cin >> f_benefits" is trying to read a double value. You should read the response into a char or string. Reading into a string expects a newline before returning.
You should also check that you got an "F" or "P" .
I am trying to read a file named elect12.csv elect12.csv sample in Excel and get the values in the last column (state) and compare it with a user inputted variable (stateCode). However, every time I run my program I am unable to prompt the user to reinput the value. How can I get this working? Thanks.
//Read popular votes file
ifstream pVotesFile ("elect12.csv");
for (int i = 0; i < statecount; i++)
{
if(pVotesFile.is_open())
{
cout << "Enter state code: ";
cin >> stateCode;
while (pVotesFile >> obama >> romney >> other >> total >> state)
{
if (stateCode == state)
{
statePoints = ((double)(obama - romney) / total) * 100;
stateTotal += statePoints;
}
else
{
cout << "Enter state code: ";
cin >> stateCode;
stateTotal = 0;
}
}
}
If the picture happens to go down sometime in the future, here is what the first few lines of the file look like:
"795696 1255925 22717 2074338 AL"
"122640 164676 13179 300495 AK"
"1025232 1233654 40368 2299254 AZ"
"394409 647744 27315 1069468 AR"
"7854285 4839958 344304 13038547 CA"
"795696
You have extra quoatation marks in the file. As a result, cin >> integer_value; will fail, because it encounters text. You should change the data like so
795696 1255925 22717 2074338 AL
122640 164676 13179 300495 AK
1025232 1233654 40368 2299254 AZ
394409 647744 27315 1069468 AR
7854285 4839958 344304 13038547 CA
Use cout to make sure you are actually reading something:
if (pVotesFile.is_open())
{
cout << "Enter state code: ";
cin >> stateCode;
while (pVotesFile >> obama >> romney >> other >> total >> state)
{
cout << obama << ", " << romney << ", " << other << ", " << total << ", "
<< state << "\n";
if (stateCode == state)
{
cout << "state found\n";
}
}
}
Alternatively, keep the data as is, then skip the first " quotation mark.
Any help would be appreciated. All I'm trying to do is ask for user input, do some calculations and print the results in a file. I thought that my code was correct but when I run my program, I get nothing. Here is my code. Not looking for an answer, just for any tips to lead me in the right direction. Thanks.
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class Employee{
private:
int id;
int job_class;
int years_service;
int Ed;
float salary;
public:
void getData(ifstream&);
void computation(int job_class, int years_service, int Ed);
void printout(ofstream&);
};
void Employee::getData(ifstream& infile){
infile >> id >> job_class >> years_service >> Ed;
}
void Employee::computation(int job_class, int years_service, int Ed){
int basePay = 800;
float jobresult, Yearresult, Edresult;
if(job_class == 1){
jobresult = .05;
}
if(job_class == 2){
jobresult = .10;
}
if(job_class == 3){
jobresult = .15;
}
if(years_service <= 10){
Yearresult =.05;
}
if(years_service > 10){
Yearresult = .05;
}
if(Ed == 1){
Edresult = .00;
}
if(Ed == 2){
Edresult = .05;
}
if(Ed == 3){
Edresult = .12;
}
if(Ed == 4){
Edresult = .20;
}
salary = basePay + jobresult + Yearresult + Edresult;
//cout << salary;
}
void Employee::printout(ofstream& outfile){
outfile << "ID: " << "Salary " << endl;
outfile << id << salary;
}
int main(){
Employee emp; //created an Employee object
string input;
int id;
int job_class;
int years_service;
int Ed;
int basepay = 800;
cout << "Enter id" << endl;
cin >> id;
cout << "Enter job_class" << endl;
cin >> job_class;
cout << "Enter years of service" << endl;
cin >> years_service;
cout << "Enter education" << endl;
cin >> Ed;
ifstream inFile;
ofstream outFile;
//getline(cin, input);
inFile.open("example.txt");
outFile.open("examplee.txt");
//inFile.open(input);
std::string r = std::to_string(id); //converted id to string
inFile.open(r);
getline(cin, r);
std::string s = std::to_string(years_service);
inFile.open(s);
getline(cin, s);
std::string t = std::to_string(years_service);
inFile.open(t);
getline(cin, t);
std::string u = std::to_string(Ed);
inFile.open(u);
getline(cin, u);
if(inFile.is_open()){
emp.getData(inFile);
inFile.close();
}
outFile.open(r);
if(outFile.is_open()){
emp.computation(job_class, years_service, Ed);
float sal = basepay + job_class + years_service + Ed;
outFile << "ID " << "Salary " << endl;
outFile << id << sal;
outFile.close();
return 0;
}
}
What exactly are you trying to do with things like this?
std::string r = std::to_string(id); //converted id to string
inFile.open(r); /*Opens a file whose name is <id> ???*/
getline(cin, r); /*Overwrites the contents of r and does nothing??? */
Your entire program is fairly confusing. My best guess as to the (main) problem is that you aren't writing anything to inFile at all. Those 12 lines after outFile.open("examplee.txt") seem like they are trying to accomplish the following:
inFile << id << ' ' << job_class << ' ' << years_service << ' ' << ED << '\n';
Also, although I'm guessing this is for debugging purposes, but many of your methods do nothing or are unused. For example, you use emp.computation(job_class, years, ED) but after that you don't use emp at all in any way. And the three lines after that seem to mimic the behavior of Employee::computation and Employee::printout.
I suggest you carefully consider the specific steps you're trying to take, then think about the purpose of methods like getline and fstream::open, and ask yourself "Does this accomplish the task I had in mind?". Because I'm really struggling to understand what you are trying to do when I read this code.
I am currently learning C++ in school and one of our projects is to create a program to calculate a budget. When I run my program, the loop that accepts the input for item cost will take the input once and then reuse that value each time it loops back. I have already searched online for a solution and my teacher is just as confused about it as I am. It could be that there is a problem with Codeblocks but I have already tried it with a different editor. If anyone knows how I can fix it, that would be great.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
//Declares variables
float itemCount = 0;
float taxPercent = 0;
float itemCost = 0;
bool taxable = true;
float totalTaxable = 0;
float totalNontaxable = 0;
float total = 0;
//Receive user input
cout << "How many items to you have to buy: ";
cin >> itemCount;
cout << "\nWhat is the tax percentage (do not include the % sign): ";
cin >> taxPercent;
//This code runs once for every item
while (itemCount > 0){
//Receive the remaining user input
cout << "\nWhat is the cost of the item: ";
cin >> itemCost;
cout << "\nIs the item taxable (Please use either true or false): ";
cin >> taxable;
//Adds the item cost to either the taxable or nontaxable variables
if (taxable == true){
totalTaxable += itemCost;
cout << "true";
} else{
totalNontaxable += itemCost;
cout <<"false";
}
itemCount -= 1;
}
total = (totalTaxable * (1 + (taxPercent / 100))) + totalNontaxable;
cout << "\n--------------------------------------------------\n";
cout << "You must earn $";
cout << total;
cout << " to meet this budget\n\n";
}
As said in the comment, you can't use cin on boolean. From the doc :
The standard input stream is a source of characters determined by the environment.
So here's your fixed code (which will accept Y and nothing else) :
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
//Declares variables
float itemCount = 0;
float taxPercent = 0;
float itemCost = 0;
char taxable = '';
float totalTaxable = 0;
float totalNontaxable = 0;
float total = 0;
//Receive user input
cout << "How many items to you have to buy: ";
cin >> itemCount;
cout << "\nWhat is the tax percentage (do not include the % sign): ";
cin >> taxPercent;
//This code runs once for every item
while (itemCount > 0){
//Receive the remaining user input
cout << "\nWhat is the cost of the item: ";
cin >> itemCost;
cout << "\nIs the item taxable (Please use Y for Yes): ";
cin >> taxable;
//Adds the item cost to either the taxable or nontaxable variables
if (taxable == 'Y'){
totalTaxable += itemCost;
cout << "true";
} else{
totalNontaxable += itemCost;
cout <<"false";
}
itemCount -= 1;
}
total = (totalTaxable * (1 + (taxPercent / 100))) + totalNontaxable;
cout << "\n--------------------------------------------------\n";
cout << "You must earn $";
cout << total;
cout << " to meet this budget\n\n";
}
Well I'm making an program about payrolls and I'm stuck. In the program, after the user has entered the number of employees, I have to make an loop, allowing the user to enter information for each of the employees. Then the data entered is to be stored in my employees array, which I made. Ive attempted my problem with the while(numberOfEmployees < MAXSIZE) part of my program. Is that right?
This is what I have now:
#include <iostream>
using namespace std;
const int MAXSIZE = 20;
struct EmployeeT
{
char name[MAXSIZE];
char title;
double gross;
double tax;
double net;
};
EmployeeT employees[MAXSIZE];
int main()
{
cout << "How many Employees? ";
int numberOfEmployees;
cin >> numberOfEmployees;
while(numberOfEmployees > MAXSIZE)
{
cout << "Error: Maximum number of employees is 20\n";
cout << "How many Employees? ";
cin >> numberOfEmployees;
}
int name;
int title;
double gross;
double tax;
double net;
for (int count=0; count<numberOfEmployees; count++)
{
cout << "Name: \n";
cin >> employees[ count ].name;
cout << "Title: \n";
cin >> employees[ count ].title;
cout << "Gross: \n";
cin >> employees[ count ].gross;
cout << "Tax: \n";
cin >> employees[ count ].tax;
cout << "Net: ";
cin >> employees[ count ].net;
}
}
I just updated it to this. My last question is how do I get the second loop to keep working as many times as the user wants. For as many employees the user types in?
Several problems:
1- Place a i++ somewhere inside the while loop
(Why not use a for loop?)
2- name and title should probably be a string:
#include <string>
//in the main:
std:string name;
3- the while condition should be:
while(i<numberOfEmployees && i<MAXSIZE)
(Edit: I see you just corrected that one)
Edit: I just noticed you always write to the same variables. Write to employees[i].name etc. instead.
Does that solve your problem?
You need something like that:
int i = 0;
while(i < numberOfEmployees && i < MAXSIZE) {
// some action here
i++;
}
or:
for(int i = 0; i < numberOfEmployees && i < MAXSIZE; i++) {
//some action here
}
Also you can just choose a minimum number of numberOfEmployees and MAXSIZE to build a condition with:
numberOfEmployees = numberOfEmployees <= MAXSIZE ? numberOfEmployees : MAXSIZE;
for(int i = 0; i < numberOfEmployees; i++) { ... }
UPD: as for for the first loop you can change the condition to numberOfEmployees > MAXSIZE and remove inner if clause
The first loop, when you check if the user enters a too large value, it never ends! Instead of doing while (true), just use while (numberOfEmployees > MAXSIZE) and skip the if (but not the content inside the if).
Also, since you already make surenumberOfEmployees is valid, you don't need the && i < MAXSIZE condition in your second loop.
how do I get the second loop to keep working as many times as the
user wants. For as many employees the user types in?
for (int count=0; count<numberOfEmployees; count++)
{
cout << "Name: \n";
cin >> employees[ count ].name;
cout << "Title: \n";
cin >> employees[ count ].title;
cout << "Gross: \n";
cin >> employees[ count ].gross;
cout << "Tax: \n";
cin >> employees[ count ].tax;
cout << "Net: ";
cin >> employees[ count ].net;
//Ask user if he wants to add more employees, if no break the loop else iterate again
cout<<"Do u want to continue: 1 to continue 0 to exit");
cin>>flag;
if(flag==0)
break;
}
}