I am having issues with string concatenation [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am using orwell dev| c++
C++ is a new language to, i am coming from c# which is like i would say 70% the same.
here is my code
#include<iostream>
#include<fstream>
using namespace std;
///loading libraries
float const taxnet = .9;
float const taxwh = .1;
int employeenumber;
float payrate, gross, net, manhours, overtime, taxes;
///declaring variablies and costants
char more;
char more2;
///user controls
///payroll calculations function
void payrollcalc () {
if (manhours>40) {
overtime= manhours-40;
gross= ((manhours - overtime) * payrate)+((payrate * 1.5)* overtime);
//overtime claculation
}
else {
gross =manhours * payrate;
//no overtime calculation
}
taxes= gross * taxwh;
net = gross * taxnet;
//taxesand net pay calculation
cout<< " Your ID is " << employeenumber <<endl;
cout<< " # of hours worked " << manhours << endl;
cout<< " Your Hourly rate is " << payrate << endl;
cout<< " Your Gross pay is " << gross << endl;
cout<< " Your tax rate is " << taxwh << endl;
cout<< " Amount of taxes " << taxes << endl;
cout<< " Your net pay is " << net << endl;
///writing to file
std::string empnum = std::to_string(employeenumber);
ofstream payroll;
payroll.open (empnum+".txt");
payroll<< " Your ID is " << employeenumber <<endl;
payroll<< " # of hours worked " << manhours << endl;
payroll<< " Your Hourly rate is " << payrate << endl;
payroll<< " Your Gross pay is " << gross << endl;
payroll<< " Your tax rate is " << taxwh << endl;
payroll<< " Amount of taxes " << taxes << endl;
payroll<< " Your net pay is " << net << endl;
payroll.close();
}
main(){
while (more != 27){
//main
cout<< "Hit 1 to enter data hit 2 to recall dat hit esc to exit";
///instructions
newdata:
///call back see line 115
if (more == 49) {
cout<< "Enter Employee ID:";
cin>> employeenumber;
cout<<"Enter Number of Hours Worked:";
cin>> manhours;
cout<<"Enter Pay rate:";
cin>> payrate;
cin>> payrollcalc;
}
else (more == 50) {
olddata:
///call back see line 111
errorreset:
cout<< "Enter employee number";
cin>> employeenumber;
///reading in data
ifstream payroll = employeenumber;
payroll.open(employeenumber".txt");
if (!payroll){
cout>> "Check employeenumber and try agian" endl;
goto errorreset:
///error check
}
cout>> payroll.eof endl;
cout>> endl;
cout>> endl;
cout>> "Press Enter to see another employee number; Press space to enter new employee information; press escape to exit the program" endl;
if (more2 == 13 ){
goto olddata;
}
else (more2 == 32){
goto newdata;
}
///sending back to the loop
}
//entering data
return 0;
}
}
I think my issues is in this segment
std::string empnum = std::to_string(employeenumber);
ofstream payroll;
payroll.open (empnum+".txt");
payroll<< " Your ID is " << employeenumber <<endl;
payroll<< " # of hours worked " << manhours << endl;
payroll<< " Your Hourly rate is " << payrate << endl;
payroll<< " Your Gross pay is " << gross << endl;
payroll<< " Your tax rate is " << taxwh << endl;
payroll<< " Amount of taxes " << taxes << endl;
payroll<< " Your net pay is " << net << endl;
payroll.close();
If some can step me through where i am going off the rails i would be grateful because i am out of ideas.

First off consider turning up the error/waring level of your compiler, for gcc/clang a sensible level would be -Wall -Wextra for a start.
Let me go through some of the problems I see in your code.
main(){
We got a first problem here already. The only 2 signatures allowed for the main function in C++ are int main() or int main(int argc, char *argv[]). Yours might be accepted due to legacy reasons (implicit return type of int in C if you don't specify any) but shouldn't be used.
cout>> payroll.eof endl; // this line absolutely makes no sens and you forgot some `<<` in here probably.
cout>> endl;
cout>> endl;
cout>> "Press Enter to see another employee number; Press space to enter new employee information; press escape to exit the program" endl;
The 'arrows' point into the wrong direction. It should be cout << endl. To remember it see them as arrows that signify the data flow. cin >> variable the data is read from cin and gets put into the variable, cout << variable the variable gets output into cout.
Then you got a read that doesn't make sense:
cin>> payrollcalc;
payrollcalc is a function, I don't know what you wanted to do here, but you should probably call it like payrollcalc();, trying to read from cin into it doesn't make sense.
You're also using std::string without #include <string>. Also note that you should probably put a space in the include line like I did. I don't know if it's a problem without space of the top of my head but it's certainly more readable with a space.
Now for some bad practices and other stuff that I should probably point out. Your indentation and formatting were very messy and made it hard to spot anything you should probably see into cleaning it up a bit.
As for goto it's considered bad practice/harmful. This was started by Dijkstra. Now to say it got it's uses still in some places and is often over exaggerated but for the simple code you're using I don't think it's necessary and could probably be done in a better more structured way that makes the logic easier to understand, remember code is read far more often than you write it and readability is very important. If you're curious about the problems, #itsnotmyrealname posted a link on your question already for you to look through.
Also you got inconsistencies that make it harder to read/confusing.
gross =manhours * payrate; // inconsistent assignments
taxes= gross * taxwh;
net = gross * taxnet;
std::to_string(employeenumber) // inconsistent function calls.
payroll.open (empnum+".txt");
As for the global variables if you've already got some experience in programming (in C# like you said) then you probably know that they are considered bad practice too and should be avoided, you should look into making them local variables and passing them around as function arguments/returning them from functions.

Related

Need Help Displaying Percentage Sign in C++

Essentially, I want the output to look like the first photo, but my output is in the 2nd (both attached). I attached my code snippet as well to show what I am trying.
Any help would be appreciated, I have solved all logical errors in this program and just need help formatting. Also, is there any better way to keep all of the inputs and calculated values on the right side, or do I just need to throw in the \t a couple times like I did? Thanks!
I want my code to look like this:
But keep getting this:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double loanAmount, interestRate, paymentsNum;
//Stores the loan amount value into memory
cout << "Loan Amount: \t\t\t$ ";
cin >> loanAmount;
//Stores the monthly interest rate value into memory
cout << "Monthly Interest Rate: \t\t";
cin >> interestRate; cout << '%' << endl;
interestRate = interestRate / 100;
//Stores the nuumber of payments value into memory
cout << "Number of Payments: \t\t";
cin >> paymentsNum;
//Calculates the payment on a loan
double payment = (interestRate * pow((1 + interestRate), paymentsNum)) / (pow((1 + interestRate), paymentsNum) - 1);
//Calculates the monthly payment on a loan
double monthlyPayment = payment * loanAmount;
cout << "Monthly Payment: \t\t$ " << monthlyPayment << endl;
//Calculates the total amount paid back from the original loan amount
double paidBack = monthlyPayment * paymentsNum;
cout << "Amount Paid Back: \t\t$ " << paidBack << endl;
//Calculates the total interest paid on the loan
double interestPaid = paidBack - loanAmount;
cout << "Interest Paid: \t\t\t$ " << interestPaid << endl;
return 0;
}
cin >> interestRate;
At this point your program stops and waits for you to type a line of text following by the Enter key, which gets echoed back, the Enter key causes the cursor to move to the next line.
cout << '%' << endl;
Only after the cursor moves to the next line does this output take place. The fact that in the source file this statement is on the same line is immaterial. The output of the C++ program does not depend on how its source code is formatted, C++ does not work this way. C++ is whitespace-agnostic, a C++ program can be indented in any way and its spacing is completely arbitrary, without affecting its functionality.
It is not possible to get the behavior you want from a basic C++ program that uses basic C++ input and output, via std::cin and std::cout, in a portable manner. On an outside chance you can consult the documentation for your operating system, to determine if there are special terminal character sequences that can be used to move the cursor to the previous line and position it at a (guessed) column where the % would go. This would be specific not just to your operating system but also to whatever terminal program you are using.
I figured out a workaround to this. To get my desired output I used:
cout << "Loan Amount: " << right << setw(20) << "$ ";
cin << loanAmount;
cout << "Monthly Interest Rate: " << setw(12) << "%\b\b";
cin >> interestRate;
interstRate = interestRate / 100;
Not sure if this is the best idea, but it worked. I'm not too worried about fixing this minor issue, but I ended up just stumbling upon this again while watching some videos online.

C++ basic converting and then adding up user inputs

This is my attempt at a solution I wrote for an exercise in Bjarne Stroustrup's Programming Principles and C++ book. Unfortunately, the section I wrote to give the total amount of money from the coins entered is not working how I would like!
A quick answer and I would be very grateful but if anyone also has the time could they help me introduce some basic error checking?
The way I would want it to work would be after a user input is required (e.g How many 20p's do you have?), to check whether or not the user inputted an int. If not, provide a subtle error message and a chance to repeat the same question, rather than stop the program or start the program from the beginning!
#include "../../std_lib_facilities.h"
int main() {
int one, ten, twenty, fifty, one_pound, two_pound;
double amount;
amount = (one * 0.01) + (ten * 0.1) + (twenty * 0.2) + (fifty * 0.5) + one_pound + (two_pound * 2);
cout << "Welcome to the change counter app!\nHow many 1p's do you have?\n";
cin >> one;
cout << "How many 10p's do you have?\n";
cin >> ten;
cout << "How many 20p's do you have?\n";
cin >> twenty;
cout << "How many 50p's do you have?\n";
cin >> fifty;
cout << "How many £1 coin's do you have?\n";
cin >> one_pound;
cout << "How many £2 coin's do you have?\n";
cin >> two_pound;
cout << "You have: " << one << " 1p coins!\n"
<< "You have: " << ten << " 2p coins!\n"
<< "You have: " << twenty << " 20p coins!\n"
<< "You have: " << fifty << " 50p coins!\n"
<< "You have: " << one_pound << " £1 coins!\n"
<< "You have: " << two_pound << " £2 coins!\n"
<< "The total amount of money you have is: " << amount << "\n";
}
You have two problems:
The first is that in the absence of loops, code runs from top to bottom. That means you calculate amount before you read the input.
The second problem is that when you calculate amount (currently, in the wrong place) you use the variables one, ten, etc. before they are initialized. Uninitialized local variables will have an indeterminate value, and using them will lead to undefined behavior.
The simple solution to both problems is to move the calculation of amount to after you have read the input, but before you write the output.

Compiler keeps ignoring cin values ?? help me solve

I am getting a problem while using
cin >> PayRate
and
cin >> H_worked
what could be the problem? Even the compiler doesn't show any errors but when program runs the 2nd and 3rd cin values aren't read by compiler.
Program:
#include <iostream.h>
#include<conio.h>
int main()
{
int employeeName, H_worked;
float PayRate, GrossPay, NetPay;
cout << "Please input your employee's name:";
cin >> employeeName;
cout << "Input hourly wage rate:";
cin >> PayRate;
cout << endl;
cout << "Input hours worked :";
cin >> H_worked;
cout << endl;
if (H_worked > 40)
{
H_worked = H_worked*1.5;
GrossPay = H_worked*PayRate;
cout << "Your employees gross pay for this week is" << GrossPay << endl;
NetPay = GrossPay - (GrossPay* 3.625);
cout << "Your employees net pay is" << NetPay << endl;
}
else (H_worked <= 40);
{
GrossPay = H_worked*PayRate;
cout << "Your employees gross pay for this week is" << GrossPay << endl;
NetPay = GrossPay - (GrossPay*3.625);
cout << "And your employees net pay is" << NetPay << endl;
}
return 0;
getch();
}
You declared employeeName as an int but that does not make any sense as names have letters not numbers. If you are actually entering in character data then this will cause cin to fail and that will make any subsequent call fail as well. This fits with your description of what is happening. To fix this first we need to make employeeName a std::string so we can store letters.
int employeeName, H_worked;
//becomes
std::string employeeName;
int H_worked;
Then we need to change the input method. Since a name can have spaces in it we need to use std::getline instead of >> to get the name as >> will stop when it sees a space.
cout << "Please input your employee's name:";
std::getline(std::cin, employeeName);
You also have a semicolon at the end of your else condition
else (H_worked <= 40);
This means that
{
GrossPay = H_worked*PayRate;
cout << "Your employees gross pay for this week is" << GrossPay << endl;
NetPay = GrossPay - (GrossPay*3.625);
cout << "And your employees net pay is" << NetPay << endl;
}
Will always run as ; ends the else part.
Then we have the issue that you are using non standard includes. In standard c++
#include <iostream.h>
Should be
#include <iostream>
As all standard includes omit the .h. Since all of the standard components live in the std namespace you are also going to have to deal with that. You can either put std:: in front of all the std components or you can put using std::cout;, using std::cin, ect. I would not suggest using using namespace std; for the reasons outlined in Why is “using namespace std;” considered bad practice?

C++ seems to stop running at string

I'm new to C++ and development in general. Frankly, I have no idea what is going on. I'm just trying to display a string on one line, but the program is giving me a confusing error.
I would really appreciate any help.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
// This program calculates and displays to user
int main()
{
// Constants are state and county taxes.
const float STATE_TAX_RATE = 0.04,
COUNTY_TAX_RATE = 0.02;
// float variables are :
float gross_sales = 0,
net_sales = 0,
county_tax_payment = 0,
state_tax_payment = 0,
total_tax_payment = 0;
// string variable
string month;
// integer variable
int year;
// Get month, year, and sales information from user
cout << "For what month is this? (Please type the name of the month.)\nAnswer: ";
getline(cin, month);
cout << "For what year?\nAnswer: ";
cin >> year;
cout << "How much was total sales at the register?\nAnswer: ";
cin >> gross_sales;
// Calculate the net income
net_sales = (gross_sales)/(1 + STATE_TAX_RATE + COUNTY_TAX_RATE);
// Calculate total taxes paid.
total_tax_payment = (gross_sales - net_sales);
// cout << total_tax_payment; // output test
// Calculate total state taxes paid.
state_tax_payment = (total_tax_payment * (2.0/3.0));
// cout << state_tax_payment; //output test
// Calculate county taxes paid.
county_tax_payment = (total_tax_payment * (1.0/3.0));
//Display the information
cout << "Month: " << month << " " << year << endl;
cout << "--------------------" << endl;
cout << "Total collected:\t $" << fixed << setw(9) << setprecision(2) << right << gross_sales << endl;
cout << "Sales: \t\t\t\t $" << fixed << setw(9) << setprecision(2) << right << net_sales << endl;
cout << "County Sales Tax:\t $" << fixed << setw(9) << setprecision(2) << right << county_tax_payment << endl;
cout << "State Sales Tax:\t $" << fixed << setw(9) << setprecision(2) << right << state_tax_payment << endl;
cout << "Total Sales Tax:\t $" << fixed << setw(9) << setprecision(2) << right << total_tax_payment << endl;
return 0;
}
The output looks like this:
For what month is this? (Please type the name of the month.)
Answer: March
For what year?
Answer: 2008
How much was total sales at the register?
Answer: 26572.89
(lldb)
At "(lldb)" The program just stops... and Xcode indicates something I don't understand on "cout << "Month: " << month << " " << year << end;", telling where an issue is, then a lot of complex debugging info. The indicator is green colored.
Thanks again for any help!!!
Because state_tax_payment and total_tax_payment are not initialize state_tax_payment = net_sales / state_tax_payment; and county_tax_payment = net_sales / county_tax_payment; lines can be result in undefined behavior
Initialize the all float variables
Assign some value to state_tax_payment and total_tax_payment
Correct the type mention by ' Thomas Matthews'.
Then your program works fine . May be it exit after execution finish. so you can add something like 'getchar()' , std::cin.get() to pause the console.
The actual problem was identified by Tony D.
The debugger in Xcode had a breakpoint set to the particular line of code. I simply had to drag it out of the gutter. For those who don't know, that the green arrow on the left in of the lines of code is a breakpoint. Drag it to the bottom, out of the code, to remove it.
I'm sure I made a total newbie mistake, since I am one, but lesson learned.

Need help debugging my first program, Visual Studio cant find the .exe file.

This is my first program its to calculate commute cost. Visual Studio is having issues debugging so Im looking for some help...
#include <iostream>
using namespace std;
int main()
{
int miles, gallons, gallonCost, mpg, mileCost, parking, tolls, FuelCost, TotalCost = 0.0;
Can someone explain what the above line is doing (or not doing) is it a correct way to make a list of float integers?
cout << " How many miles do you drive per day? ";
cin >> miles;
cout << " What is the price per gallon of fuel? ";
cin << gallonCost;
cout << " How many gallons of fuel do you use per day? ";
cin >> gallons;
mpg = miles / gallons;
mileCost = gallonCost / mpg;
cout << " Your fuel efficentcy is " << mpg ;" miles per gallon. ";
cout << " Your fuel cost is $" << mileCost ;" per mile. ";
FuelCost = mileCost * miles;
cout << " Your paying $" << FuelCost ;" for fuel per day.";
cout << " What are you daily parking fees? ";
cin << parking;
cout << " How much do you spend on Tolls each day? ";
cin >> tolls;
TotalCost = parking + tolls + FuelCost;
cout << " Your driving cost is $" << TotalCost ;" per day." endl;
system("PAUSE");
return 0;
}
Thanks in advance
No that is not the way to create floating point variables, but the way to create integer variables. There is no such things as "float integers".
You should also get a lot of warnings about expressions not doing anything, like in the line
cout << " Your fuel efficentcy is " << mpg ;" miles per gallon. ";
// Problem here ^
That is because you have an extra semicolon in the middle of the line, thereby terminating the output statement. Then the compiler finds a string, which is the same as an expression so it's okay but doesn't do anything which should cause a warning. Instead of the extra semicolon I suspect you wanted the output operator <<.
And you should be getting an error on this line:
cout << " Your driving cost is $" << TotalCost ;" per day." endl;
// Error here ^
That error is because you have a string followed by an identifier. This is not a valid expression. You probably forgot the output operator << here.
It's this last error that causes the build process to not create an executable, so you can't run/debug. Always pay attention to the messages produced by the compiler, even warnings will tell you something useful.