I have wrote some basic code for a project. I am at the point I am trying to take an input from a RFID reader using a keyboard emulator. The follwing is my code to this point:
#include <iostream>
#include <ios>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
char product; //declaring the variable for the switch/case
int Pay = 0; //Declaring the variable Pay
int Payment = 0;
double Total = 0; // Declaring the Final Total variable
double Subtotal = 0; // Declaring the variable Subtotal
double Tax = 0; // Declaring the variable Tax
int m = 0; //counts the amount of times milk is scanned
int b = 0; //counts the amount of times beer is scanned
int c = 0; //counts the amount of times candy bar is scanned
int r = 0; //counts the amount of times rice is scanned
cout << "Scan the product you desire to purchase: \n";//Asking user to input product purchasing
cout << "When ready to checkout press the z button.\n\n\n"; //Telling user to press button z to pay
while(Pay < 1) //Keeps in the loop until pay is increased to 1
{
getline(cin, product); //Taking input and assining to the variable product
if(product == E007C02A55EF918D)
{
cout << "6 pack of Budlight...........$6.49\n"; // If the button b is pushed displays
Subtotal = Subtotal + Beer; // Calculates the Subtotal and stores it
Tax = Beer * Taxrate + Tax; // Claculates the total Tax and stores it
b++;
}
else if(product == E007C02A55EF937C)
{
cout << "Snickers Bar.................$0.99\n";// If the button c is pusehd displays
Subtotal = Subtotal + Candy_Bar;
Tax = Candy_Bar * Taxrate + Tax;
c++;
}
else if(product == E007C02A554A7A8B)
{
cout << "1 Gallon of 2% Milk..........$3.99\n";//If the button m is pushed displays
Subtotal = Subtotal + Milk;
m++;
}
else if(product == E007C02A55CE0766)
{
cout << "Box of Brown Rice............$2.79\n";//If the button r is pushed displays
Subtotal = Subtotal + Rice;
r++;
}
else
cout << "Invaild product. Please scan a different product.\n";
if (product == 'z')
Pay++; //When finished it increases pay to 1 to break the while loop
Total = Subtotal + Tax; // Claculates the Total
}
I am using MSVS 2010 to compile this code. With this code I can not compile because it says E007C02A55EF918D is undefined. E007C02A55EF918D is the serial number from one of the RFID tags and is what I am trying to input. I know I am having problems with the getline function also, but I am more worried about getting the serial number as an input.
char is big enough for a single character (it is usually an 8bit quantity, but don't rely on that).
So your product variable can only hold one char.
E007C02A55EF918D is an identifier (because it begins with a letter, it is not considered as a number, and because it is not quoted, it is not interpreted as a string).
If you intended product and those serial numbers to be 64bit numbers, you'll need to change product to be large enough to store them (uint64_t for instance), and change the serial numbers in your code to be numbers by prefixing with 0x. You'll also have to change your input method (getline takes strings, so you will need to convert that string to a number - see How to convert a number to string and vice versa in C++ for instance).
if (product == 0xABCD1234)
If you indented both to be strings, then declare product with:
std::string product;
and quote ("") the serial numbers. You'll also need to change the last test to:
if (product == "z")
^ ^
You can't compare an std::string with a single char ('z' is a char, "z" is a C-style 0-terminated string).
Try having it in "" and use strcmp() instead of ==, like
if (!strcmp("E007C02A55EF937C",product))
or
if (strcmp("E007C02A55EF937C",product)==0)
Hope it helped you.
Related
I'm new to C++ and I have to make a program that lets the user enter a specified number of test scores and calculate the average, highest, and lowest scores. (It doesn't have to check if values are between 1 and 100.) For some reason, when it goes to print out the average score and sum of the scores, it just prints out random exponential numbers that are never the same. I haven't gotten to printing out the lowest and highest scores yet since I'm not sure if I'm even doing the average right. Again, I'm new to C++ so I'm sure I messed something up. Here's the code:
#include <iostream>
using namespace std;
int loopLimit = 0; //number of scores or how many times it will loop
double *testScores = {0}; //array scores are stored in
int main () {
cout << "How many test scores are you entering?" << endl;
cin >> loopLimit;
testScores = new double[loopLimit]; //changes array to needed size
for (int i = 0; i < loopLimit; i++) {
cout << "Enter test score #" << (i + 1) << endl;
cin >> *testScores;
}
double sum = 0.0;
double average = 0.0;
//double max = 0.0; //making these functions later
//double min = 0.0;
sum += testScores[loopLimit];
average = sum / loopLimit;
//Sum is here for testing purposes at the moment
cout << "Sum = " << sum << " Average = " << average << endl;
return 0;
}
Example output 1:
How many test scores are you entering?
3
Enter test score #1
100
Enter test score #2
100
Enter test score #3
100
Sum = 8.29874e-310 Average = 2.76625e-310
Example output 2:
How many test scores are you entering?
3
Enter test score #1
100
Enter test score #2
100
Enter test score #3
100
Sum = 8.94176e-310 Average = 2.98059e-310
Expected output:
How many test scores are you entering?
3
Enter test score #1
100
Enter test score #2
100
Enter test score #3
100
Sum = 300.0 Average = 100.0
I've been at this all week, and I honestly got nothing at this point.
OK, let's go over your code.
#include <iostream>
using namespace std;
Why are you importing all identifiers in std:: here? using namespace std; is not recommended.
int loopLimit = 0; //number of scores or how many times it will loop
double *testScores = {0}; //array scores are stored in
Bad: You should avoid global variables unless they're absolutely necessary. 99.9% of the time they're not. These could easily be local variables in main.
testScores is not an array, it's a pointer. Initializing it with {0} is just a weird way of writing testScores = nullptr;.
int main () {
cout << "How many test scores are you entering?" << endl;
cin >> loopLimit;
testScores = new double[loopLimit]; //changes array to needed size
You're using manual memory management here. Not technically wrong, but it would be much easier and less error prone to use a std::vector instead.
for (int i = 0; i < loopLimit; i++) {
cout << "Enter test score #" << (i + 1) << endl;
cin >> *testScores;
This line stores every input in *testScores, i.e. the location pointed to by testScores, which corresponds to the first index of the array allocated by new above. This means only testScores[0] is initialized (ending up containing the last number the user input), every other index is uninitialized.
You should use cin >> testScores[i] instead.
}
double sum = 0.0;
double average = 0.0;
//double max = 0.0; //making these functions later
//double min = 0.0;
sum += testScores[loopLimit];
This is an invalid memory access. As testScores points to a dynamic array of size loopLimit, the valid array indices go from 0 to loopLimit-1. Therefore testScores[loopLimit] accesses memory past the bounds of the array.
Also, it's just one element you're adding here. Even if this were a valid array index, this could would still make no sense. You should loop over all array elements here (like your for loop above), or just do this part of the calculation in your other loop. In fact, there's no need to store all numbers in memory if all you're interested in is their sum (which you can compute directly as you're reading the input).
average = sum / loopLimit;
average is computed from sum, which has a garbage value, so it's garbage too.
//Sum is here for testing purposes at the moment
cout << "Sum = " << sum << " Average = " << average << endl;
... and this is why you're getting garbage output.
return 0;
Here you're leaking the memory allocated with new. This is not really a problem in this case because your program is about to exit anyway, but in general you want delete[] testScores; here (unless you use a std::vector, which takes care of cleaning up for you).
}
A couple of things, first the line
cin >> *testScores;
is not storing the test scores in an array (I think this is what you want to do) instead at every iteration the new test score is being stored in the first element i.e testScores[0], rewriting the old value.
Next,
The line
sum += testScores[loopLimit];
looks outside the array. This means that you are looking at a random place in memory which probably has junk in it. That explains why you are seeing random numbers outputted.
Try to fix those two issues. If you don't need to save the test scores you can away keep a running sum of them, that would eliminate the need to store everything in an array.
I don't know why you want to write such a messed up code for just calculating average.But here's my approach.
Since you entered loopLimit value as 3.So according to your code,sum will contain have the value of sum[3].That is a garbage value.Since indexing starts with 0 and not 1.So your sum will have a garbage value and that is the reason why you are getting such incorrect value.I have modified your code and it works fine for me.
int loopLimit;
cout << "How many test scores are you entering?" << endl;
cin >> loopLimit;
double scores[loopLimit];
double sum=0.0;
for (int i = 0; i < loopLimit; i++)
{
cout << "Enter test score #" << (i + 1) << endl;
cin >> scores[i];
sum+=scores[i];
}
double avg=sum/loopLimit;
cout << "Sum = " << sum << " Average = " << avg << endl;
return 0;
Try avoiding using pointers during the early stage of programming as it can really mess up with your brain and can create problems.Try to go for a simple approach.
The possible issue is that you're doing this
double* testScores = {0};
which will initialize it to nullptr, potentially letting you read and write garbage data. What you should use instead is probably a dynamic resizing array such as
std::vector<double> testScores;
and to add a score to the list
double inScore = 0;
std::cin >> inScore;
testScores.push_back(inScore); // This adds to the list of scores.
#include <iostream>
using namespace std;
int loopLimit = 0; //number of scores or how many times it will loop
double *testScores = {0}; //array scores are stored in
int main () {
double sum = 0.0;
double average = 0.0;
cout << "How many test scores are you entering?" << endl;
cin >> loopLimit;
testScores = new double[loopLimit]; //changes array to needed size
for (int i = 0; i < loopLimit; i++) {
cout << "Enter test score #" << (i + 1) << endl;
cin >> testScores[i];
sum += testScores[i];
}
average = sum / loopLimit;
cout << "Sum = " << sum << " Average = " << average << endl;
delete [] testScores;
return 0;
}
*melpomene is right...that pointer "testScores" wont increment through your for loop so the array occupies garbage also put sum += testScores[i] in the loop to sum your input.
I'm currently working on an assignment and it's meant to take the concept of a car body shop offering different trim packages at different prices, the program is meant to use a pretest loop to stop the function if a user inputs a code that isn't already on the array, and then the user inputs the base price of their car and the program is meant to add the base price, the trim price and a 15% sales tax and give the new user their total cost. If I only had to create a function that displayed array's I think I'd have no trouble but I'm currently tearing my hair out trying to wrap my head around how to get all the different functions to work together
currently my algorithm is
1)enter the base price of car
2.) Enter the trim package code
3.) searchIndex=0
while OptionPackageCodeArray =[search index]
searchIndex++
end loop
if searchIndex<5
input packageCode
OptionPackageCode[searchIndex] = packageCode
else
Display error "This code does not exist"
end if
4.) Determine totalCost
PackageCostArray[searchIndex] + basePrice = costwithPackage
totalCost = costwithPackage*0.15
5.) display total cost
"The price of your car with Trim is" : totalCost
end loop
and the actual C++ I have written so far is
#include <iostream>
#include <string>
using namespace std;
int main()
{
//declare variables
double basePrice = 0.00;
string OptionPackageCodeArray[] = {"BB", "SP", "NP", "HE", "UC"};
double PackageCostArray [] = {1500.00, 3250.00, 4575.00, 7500.00, 5220.00};
double totalCost = 0.00
//prompt for base price
cout << "Enter base price:";
cin>>basePrice;
cout <<"enter package code: BB, SP, NP, HE, UC";
cin >> OptionPackageCodeArray;
}
however I'm stuck at this point
if anybody has any suggestions I'd be happy to take them.
you just write the code step by step. you can read blow code for reference.
double basePrice = 0.00;
static const int num = 5;
string OptionPackageCodeArray[num] = {"BB", "SP", "NP", "HE", "UC"};
double PackageCostArray [num] = {1500.00, 3250.00, 4575.00, 7500.00, 5220.00};
double totalCost = 0.00;
while(true)
{
//prompt for base price
cout << "Enter base price:";
cin>>basePrice;
std::string package;
cout <<"enter package code: BB, SP, NP, HE, UC"<<std::endl;
cin >> package;
int i = 0;
for (; i < num; i++)
{
if (OptionPackageCodeArray[i] == package)
{
break;
}
}
if (i == num)
{
break;
}
else
{
std::cout<<(basePrice + PackageCostArray[i]) * 0.15<<std::endl;
}
}
I have to write a program for a C++ class and I am having a bit of trouble. I have gone through all my variables and I feel like I initialized everything, but its still not working.
Program parameters: Calculate electrical bill. Customer gets charged $0.27 a kwh up to 500 kwh, then is charged at an extra rate of $0.57 a kwh thereafter.
Input: kwh
output: Total customer bill
Code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
//List the variables
double kwh;
double baseKwh;
double extraKwh;
double baseBill;
double extraBill;
double electricBill;
//User inputs the kwh used
cout << "Enter kwh used: "; //Prompt
cin >> kwh;
//Process the data and compute the bill
if (kwh <= 500) {
baseKwh = kwh;
extraBill = 0;
}
else {
baseKwh = 500;
extraKwh = kwh - 500;
}
baseBill = baseKwh * 0.27;
extraBill = extraKwh * 0.55;
electricBill = baseBill + extraBill;
//Output the bill.
cout << "Your bill is $" << electricBill << endl;
system("PAUSE");
return 0;
}
problem:
Run-Time Check Failure #3 - The variable 'extraKwh' is being used
without being initialized.
Microsoft Visual Studio points to line 30 as the problem. The program works fine when the user inputs above 500, however, when the user inputs 500 or below then I get the error message.
extraBill = extraKwh * 0.55;
Well if the else clause is not evaluated above this code, extraKwh is indeed uninitialized. So you are trying to read value of uninitialized variable above and triggering undefined behaviour. Assign some default value to it during declaration and that issue should go away.
In general it is good idea to initialize variables during declaration.
You have declared your variables, but left them uninitialized.
You are using extraKwh no matter what happens in your code. Judging by your logic, you should initialize it to zero at the same time it is declared:
double extraKwh = 0;
This way, there will always be a value assigned to extraKwh, even if you don't don't hit your else block.
//Purpose: To calculate the price to pay an author
//Programmer: Brandon C Ballard
//Last Updated: 2/20/2014
#include <iostream>
#include <cstdlib>
using namespace std;
//function prototype
float TotalPay(int numWords, char Level);
int main()
{
float TotalPay;
int numWords;
char Level;
int amtToPay;
cout << "Please enter number of words: ";
cin >> numWords;
cout << endl;
cout << "Please enter a Level, A,B, or C: ";
cin >> Level; cout << endl << endl;
//calculate price per word
if (numWords < 7500)
amtToPay = numWords * .08;
else if (numWords >= 7500 && numWords < 8000)
amtToPay = 600;
else if (numWords >= 8000 && numWords < 17500)
amtToPay = numWords * .075;
else if (numWords >= 17500 && numWords < 19000)
amtToPay = 1313;
else
amtToPay = numWords *.07;
//calculate the Level of the author
if (Level == 'C' or Level == 'c')
Level = 1;
else if (Level == 'B' or Level == 'b')
Level = 1.25;
else if (Level == 'A' or Level == 'a')
Level = 1.75;
TotalPay = amtToPay * Level;
cout << "Length of Story (words): "; cout << numWords; cout << endl << endl;
cout << "Amount Due Author: "; cout << "$"; cout << TotalPay; cout << endl << endl << endl;
system("PAUSE");
return 0;
}//end main function
My instructor wants me to write a program that can calculate the amount of money to pay an author who is submitting an article to a magazine. The amount of money to pay the author is based off of how many words are in the article. It works like this...
-if length (in words) is less than 7,500: the author gets paid $0.08 per word.
-if length is 7,500 to 8,000: the author gets paid a fixed $600.
-if length is 8,000 to 17,500: the author gets paid $0.075 per word.
-if length is 17,500 to 19,000: the author gets paid a fixed $1313.
-if length is greater than 19,000: the author gets paid $0.08 per word.
Also: There are three different "Levels" of authors (A,B, and C). A "C" Level author (new author) would get paid based on the information above. A "B" Level author (established writer) would get paid 1.25 times the amount of a Level C author. An "A" Level author (rockstar) would get paid 1.75 times the amount of a Level C author.
The Math: Basically, I wrote the program so that it first calculates the amount to pay the author (amtToPay). Then, it calculates what the (Level) is equal to. Then the (TotalPay) is the (amtToPay) multiplied by the (Level).
My Problem: Everything works great except for the part where it //calculates the Level of the author. For example, if I were to input the author as an "A" Level, he should get paid 1.75 times that of a Level C author. So, it should multiply the (amtToPay) by 1.75, except what is actually doing is multiplying it by "1" and is ignoring the ".75".
I am new to programming and I understand that there are probably many other ways to write this. But please try and help me the best that you can. Thank you.
Level is an integer type so when you assign the floating point numbers to it, the fractional parts are dropped.
Try defining double rateLevel and then
if (Level == 'C' or Level == 'c')
rateLevel = 1;
else if (Level == 'B' or Level == 'b')
rateLevel = 1.25;
else if (Level == 'A' or Level == 'a')
rateLevel = 1.75;
TotalPay = amtToPay * rateLevel;
The proper way to do this is to not use floating point types at all, except maybe for printouts. The way to accomplish this is to scale everything by a power of ten that will remove all fractional components from your values. In your code the least significant digit is in the thousands place (0.075). This means that you need to multiply all your values by 1000. This is called your scale factor. Then you can do your math using only integral types, int, long, int64_t, etc. At the end of your calculations you can split the results into whole number and fractional components.
Like this:
int TotalPayDollars = TotalPay/1000;
int TotalPayMilliDollars = TotalPay - 1000*TotalPayDollars;
int TotalPayCents = (int)((double)TotalPayMilliDollars/10 + 0.5);
The first line is all integer math so the dividing by 1000 discards any fractional parts.
The second line finds the difference between your original value and the truncated value. We multiply TotalPayDollars by 1000 to bring it into the same units as TotalPay again.
In the last line the + 0.5 works to round up to the nearest cent.
NOTE: when choosing a scale factor it is very important to make sure that you don't overflow your integer type. A 32 bit signed integer can only hold numbers up to 2^31-1 (2,147,483,647). If any of your calculations will go higher than that value then you should use a 64 bit integer type.
Level is type char which is integral, you should create a new variable specifically to hold the amount boosted by level:
double level_boost;
//logic
Totalpay = amtToPay * level_boost;
PS: in your logic, you do not have to use &&:
if (numWords < 7500)
amtToPay = numWords * .08;
else if (numWords < 8000)
//if the numwords is less than 7500 will be handled by first if
amtToPay = 600;
I'm really confused. I have to make this lab for a class and I can't seem to have the search only display one result but all of the months of the year. I also can't seem to figure out why its not displaying the TotalRainfall when I input 0 into the month of the year.
Thank you.
#include <iostream>
#include <fstream>
const int MaxSize = 12; //How many weather lines will be available.
using namespace std;
struct WeatherInformation
{
int Month; //Months of the year
float TotalMonthsRainfall; //Total amount of rainfall
float HighTemp; //The Highest temperature of the month.
float LowTemp; //The Lowest temperature of the month.
float AverageTemp; //The Average temperature of the month.
};
WeatherInformation WeatherArray[MaxSize]; //Declaring a month array of MaxSize
void ReadFile(ifstream& MyinFile, WeatherInformation WeatherArray[]);
void WeatherMonthSearch (WeatherInformation WeatherArray[]);
int main()
{
float TotalRainfall = 0;
int count = 1; //Counts how many times the for loop goes.
int MonthOfWeather; //User input of the month.
char ProgramRedo; //User input if they want to reuse the program.
char exit_char; //User input to exit the program.
ifstream MyinFile; //Variable that uses file.
ReadFile (MyinFile, WeatherArray); //Call ReadFile Function
WeatherMonthSearch (WeatherArray); //Call WeatherMonthSearch Function
MyinFile.close(); //Closes file.
}
//Brett Holmes
//4/30/2013
//PreCondition:You need a file labeled weather.dat
//PostCondition: It puts the file variables into an array.
void ReadFile(ifstream& MyinFile, WeatherInformation WeatherArray[])
{
float TotalRainfall = 0;
char exit_char;
int count = 0;
int Month = 0;
cout << "Your Weather Machine" << endl << endl;
MyinFile.open("weather.dat");
if (!MyinFile)
{ //no
cout << "Can't open input file." << endl; //Tests the right file.
char exit_char; //End Program
cout << "Press any key to exit" << endl;
cin >> exit_char;
}
for(count = 1; count < MaxSize; count++) //Puts the file variables in the array.
{
WeatherArray[count].Month = WeatherArray[count].Month + 1;
MyinFile >> WeatherArray[count].TotalMonthsRainfall;
MyinFile >> WeatherArray[count].HighTemp;
MyinFile >> WeatherArray[count].LowTemp;
(WeatherArray[count].AverageTemp = ((WeatherArray[count].HighTemp + WeatherArray[count].LowTemp)/2));
(TotalRainfall = TotalRainfall + WeatherArray[count].TotalMonthsRainfall);
}
}
//Brett Holmes
//4/30/13
//PreCondition:You need to have the months already put into an array in a struct.
//PostCondition:Outputs the rainfall stats the user puts in then asks to run again.
//Outputs a error message if they type in the month wrong.
void WeatherMonthSearch (WeatherInformation WeatherArray[])
{
float TotalRainfall;
int months;
int MonthOfWeather;
char ProgramRedo;
do
{
bool MonthFound = false;
cout << "Please input the number of the Month. Ex. 1=Jan. 2=Feb. etc \n\n";
cin >> MonthOfWeather;
for(int i = 1; i <= MaxSize; i++)
{
months = WeatherArray[i].Month;
if(months == MonthOfWeather ) //Finds the artist and outputs the results
{
cout << "\nTotal Months Rainfall: " << WeatherArray[i].TotalMonthsRainfall << " \n";
cout << "Highest Temperature: " << WeatherArray[i].HighTemp << " \n";
cout << "Lowest Temperature: " << WeatherArray[i].LowTemp << " \n";
cout << "Average Temperature: " << WeatherArray[i].AverageTemp << " \n";
MonthOfWeather = true;
}
}
if(MonthOfWeather == 0)
{
cout << "The total rainfall for the year is: " << TotalRainfall << ".";
}
if(MonthFound == false)
{
cout << "\nMonth Number error. Month not found. Try again.\n\n";
MonthOfWeather = false;
}
cout << "Would you like to look up another month of weather?\n";
cout << "Enter a 'Y' if yes and 'N' if no.\n";
cin >> ProgramRedo;
}while(ProgramRedo == 'Y');
}
Several obvious problems:
Arrays in C++ is 0-based, so your for loop is off-by-one. In your search function, for(int i = 1; i <= MaxSize; i++) should be for(int i = 0; i < MaxSize; i++). Similarly, in your read function, for(count = 1; count < MaxSize; count++) should be for(count = 0; count < MaxSize; count++) (If you want to skip index 0 because you are using it as a signal value, then you should set MaxSize to 13 and have the loop start at 1.)
Why are you assigning a boolean to MonthOfWeather? Do you mean MonthFound?
You read function is not setting the months correctly. WeatherArray[count].Month = WeatherArray[count].Month + 1; should be WeatherArray[count].Month = count; if you are using a 1-based loop or WeatherArray[count].Month = count + 1; if the loop is 0-based.
You calculated your total rainfall in the read function, but the result is stored in a local variable so it's lost when the read is done. Either make TotalRainfall a global variable or do your calculations in your search function.
There are a lot of redundant variable definitions: for example, your weather data array is a global so there is no reason to actually pass it around; exit_char is declared twice in your read function; the first five lines of your main() declared variables that you never used.
Also, your read function does not actually exit the program on failure - it even still attempts to read from the stream and then call your search function! If error-checking is a requirement, you should either have the read function return a boolean and check that the read function succeeded before calling your search function, or simply call std::exit after that cin >> exit_char;.
So, one problem you have is that you have local variables that appear in multiple places, but appears like you expect them to actually contain the same information.
For example, I see three different TotalRainFall. One in main, which is just there, not used for anything, one in ReadFile which is calculated, and one in WeatherMonthSearch, which is not set to anything.
I suspect you want all three of these to actually do something. One way to achieve that would be to remove the local ones in ReadFile and WeatherMonthSearch, and instead pass in the one from main (as a reference into ReadFile).
There's also a few places where you use variables without initializing them. Make it a habit to initialize EVERYTHING and EVERYWHERE!
Enable warnings in your compiler - if you have any form or reasonably new compiler (gcc or MS Visual Studio of recent vintage), it should tell you at least some of these things.