I am trying to build a program that outputs No. of people I have entered and the average of their ages. This is my code
#include <iostream>
#include <string>
using namespace std;
int main()
{
int age;
int total = 0;
int No_of_People = 0;
while (age != -1){
total = total + age;
No_of_People++;
cout << "Enter a person's age or enter -1 to stop\n";
cin >> age;
}
cout << "Number of people entered:\n" <<No_of_People<< endl;
cout << "Average age of people = "<< total/No_of_People;
return 0;
}
However the computer prints the average wrong, anyone know what i did wrong?
This is the output
I see two major problems in your code: First, age is not initialized. Reading from it leads to undefined behavior (as mentioned by UnholySheep). Everything could happen from some seemingly random value to an access violation. I once forgot to initialize a boolean variable, it was initialized with false on my computer every time I ran the program (like I intended), on another team members it was initialized to true and we wondered why it's working for me but not for him. So best initialize it with 0 like you do for total.
Second, you're adding age on total before knowing its value. So when you set age to 0 in the beginning, you will increase the number of people one more time than you increase the total age. Add age to total after asking for a value.
A third thing is, that you don't take care for -1 properly. You're increasing the number of people even if -1 is typed in. You should check for that value before increasing the number of people or adding it to your total.
Just thought I would add to Tobias Brösamle's answer.
A good hint that you did not initialize age might be that running the program multiple times with the same input values yields different results.
Have a look at these modifications, comments highlight changed code.
Mostly I see that you're a beginner in coding, your errors can be attributed to not quite developing a "working methodology" - i.e. always initialising variables. I also moved the code into a separate function, whenever I put test code in a main function it very quickly develops into needing to do this anyway.
#include <string>
#include <iostream>
using namespace std;
void age()
{
int age = 0; // not initalised
int total = 0;
int count = -1; // naming convention of previous variable didn't match other variables
do // loop terminates at bottom
{
cout << "Enter a person's age or enter 0 to stop\n"; // why \n here instead of endl?
cin >> age;
total += age;
count++;
} while (age > 0); // slightly easier code to write if 0 terminates instead of -1
cout << "Number of people entered:\n" << count << endl;
cout << "Average age of people = " << total / (float)count; // floating point result
}
int main()
{
age();
char temp;
cin >> temp;
}
you should copy the code
cout << "Enter a person's age or enter -1 to stop\n";
cin >> age;
before the while loop.
Related
Current code:
const int MAX_CODENAME = 25;
const int MAX_SPOTS = 5;
struct Team {
string TeamName[MAX_CODENAME];
short int totalLeagueGames;
short int leagueWins;
short int leagueLoses;
};
//GLOBAL VARIABLES:
Team league[MAX_SPOTS];
void addTeams(){
int i = 0; //first loop
int j; //second loop
while(i < MAX_SPOTS){
cout << "****** ADD TEAMS ******" << endl;
cout << "Enter the teams name " << endl;
scanf("%s", league[i].TeamName) ;
}
void searchTeam(){
string decider[MAX_CODENAME];
cout << "Please enter the team name you would like the program to retrieve: " << endl;
cin >> decider[MAX_CODENAME];
for(int i = 0; i < MAX_SPOTS; i++){
if(decider == league[i].TeamName){
cout << endl;
cout << league[i].TeamName << endl;
break;
}else{
cout << "Searching...." << endl;
}
}
}
I really dont know why its not working but I have included all the perquisite header files such as and but the program crashes when i enter the data and then attempt to search. I get the circle of death and then program not responding then says Process returned 255 (0xFF) . It does not even out put Searching.... the program practically gives up as soon as I enter that name.
Also if this can be optimized by the use of pointers that would be great.
tl;dr run-time error causing the search to fail as soon as i type in a name. And for the record I have checked to make sure the name I entered is valid.
scanf doesn't know about std::string. Use std::cin >> league[i].TeamName.
scanf("%s", league[i].TeamName) ;
This should be changed to
std::cin >> league[i].TeamName ;
A couple of other things here....
string decider[MAX_CODENAME];
cout << "Please enter the team name you would like the program to retrieve: " << endl;
cin >> decider[MAX_CODENAME];
Every time you input a value, you are telling the computer to hold the inputted value at decider[25] but the computer only reads indexes 0-24.
if(decider == league[i].TeamName){
Which array slot are you comparing the team name to? If its the 25th element than the statement should be
if(decider[24] == league[i].TeamName){
Pointers are better suited if the number of TeamNames are unknown. Based on the limited code presented, I highly recommend you stay within the realm of basic data types. For the purposes of troubleshooting, please post your full code in the future.
Your TeamName member variable:
string TeamName[MAX_CODENAME];
is an array of 25 strings, so in this line:
scanf("%s", league[i].TeamName) ;
you are courrupting the array. You don't really want an array anyways, so change the TeamName declaration to:
string TeamName;
and then when you read the name, you'll need to use iostreams which knows how to populate a string type (scanf only works with c char arrays):
std::cin >> league[i].TeamName
When I pass in a value and assign it to another variable, it never seems to add them together. It only outputs both totals in the file, but not together. Can anyone point out my mistake?
void financialReport(int price)
{
ofstream financial_log("financial.txt", ios::app);
int total = 0;
total += price;
int test = total++;
financial_log << "Total: " << test;
financial_log.close();
}
cout << "Destination: ";
cin >> destination;
cout << "Price agreed: ";
cin >> price;
financialReport(price);
This is the output I get in my text file:
Total4Total5
Also, for some reason, there is no space between the total and the price.
It's a little hard to understand your question but I think one issue conuld be confusion about how the ++ operator works. variable_name++ will increment the variable after its evaluation in the current statement and ++variable_name will increment the variable before its evaluation in the current statement.
In your code above, ++ has no effect. If you want your variable test to have a value of one greater than total. Then you need to do this:
int test = ++total;
However, honestly in your case, that doesn't even make sense since total isn't used anywhere in the function after that. You would be better off just simply doing:
int test = total + 1;
Try opening a separate and specific questions about any ios or in/out formatting concerns.
It also looks like you're somehow trying to come up with a total across two function calls using a local variable which will never work because total will get reset to 0 on every function call.
I would be willing to bet that if you do as A. Yurchenko suggests you will probably find your own bug.
If you want to store total value in a file, you may use this:
void financialReport(int price) {
ifstream financial_log_in("financial.txt");
int total = 0;
string dummy;
while (financial_log_in >> dummy && dummy != "Total:") {
}
if (dummy == "Total:") {
financial_log_in >> total;
}
ofstream financial_log_out("financial.txt");
total += price;
financial_log_out << "Total: " << total << endl;
financial_log_out.close();
}
Here we read the current value from financial.txt, update it and write it back.
But in case you just call the function a few times during one runtime this will be more efficient:
void financialReport(int price) {
static int total = 0;
ofstream financial_log("financial.txt");
total += price;
financial_log << "Total: " total << endl;
}
This way financialReport(5); financialReport(6); will result in Total: 11, but when you restart the program total will be 0 again.
Please, notice that both methods will overwrite financial.txt. If you don't want this behavior add ios::app flag to the constructor of the ofstream objects.
I have made a simple program in C++ and this is the code:
#include <iostream>
using namespace std;
int main()
{
int number;
int square;
number = 5;
square = number * number;
cout << "The square is ";
cout << square;
return 0;
}
what it does is basically taking the integer "5" and get the square value on the screen and so on...
my question is:
how can I make the program take any value from the user instead of storing a value in the memory?
than Q.
Your code makes use of cout to print. C++ makes cin available for input from the console:
int x;
cin >> x;
"An example is worth a thousand words..."
Well cout takes some var. from memory and prints it out on the screen, right?
Well, cin does the exact opposite, it takes in some value from the keyboard and puts it in your memory..
You have to take in the value with the help of cin command, like this:
int a; //lets say you have a variable
cout << "Enter a value here: "; //prompts the user to enter some number
cin >> a; //this line will allow the user to enter some value with the keyboard into this var.
int square = a * a;
cout << "The square is: " << square;
Hope it helps...
Just replace:
number = 5;
with:
cout << "What's the number? ";
cin >> number;
You already know how to use cout to generate output, this simply uses cin to retrieve input.
Keep in mind that, while this may be okay for small test programs or learning, data input in real programs tends to be a little more robust (such as if you enter the string xyzzy when it's trying to input an int variable).
I'm a novice user to C++ currently taking college courses in CS, and I'm stuck since my code does not read values from my input file, "OH-in.dat". Moreover, I don't quite know what to do when it comes to a sentinel value (since I require a do while loop, I think I'll just have to make the sentinel value be the first value I take and simply stop the loop from then on.)
Here's the code I have so far:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
// Declare the variables to be used in the program.
ifstream infile;
string schoolname, location;
int tuition, enrollnum, i;
double average;
//Obtain the values for the variables from the file given.
infile.open("OH-in.dat"); //Accomplish task 1.
{
i = 0;
cout << "Schools in Cincinnati with tuition below $20,000." << endl;
cout << "-----------------------------------------------------" << endl;
do
{
// Read the values in the data file.
infile >> schoolname;
infile >> location;
infile >> enrollnum;
infile >> tuition;
// Separate the values that contain Cincinnati and if it's tuition is over 20000 dollars.
if (schoolname == "Cincinnati" && tuition < 20000)
{
cout << schoolname << " $" << tuition << endl;
i++;
}
// Display the number of schools that fit the criteria.
cout << "Number of schools: " << i << endl;
}
//While the 1st value read in is not ***, the loop will continue.
while (schoolname != "***");
//Close the file.
infile.close();
}
system("pause");
return 0;
}
Here's the first four values I will be inputting.
AntiochCollege
YellowSprings
330
27800
...
Finally, it will come to this.
'* * *'
This data was collected from petersons.com
on October 10 and 11. Some name and location
data has been altered.
Now, the main two problems I've had with this code have been simply getting C++ to read in the values and secondly getting the code to not infinitely repeat itself.
You can use something like
if (infile.fail()) break;
immediately after the four "infile >>" statements. Or you can use .eof() rather than .fail() if you like. Either way, it will exit your loop when infile has no more data to give.
In your specific case, of course, you're looking for the sentinel rather than the file's end, but the same principle applies. This is an ideal case for C++'s break statement.
Incidentally, once you add the break, you probably won't want the do-while any longer. A while(true) or for(;;) -- that is, a loop whose condition always passes -- will probably serve. This loop's natural exit point is in the middle, at the break you will add to it.
I am usually a Java programmer, and have used textmate for that almost exclusively, but lately I started using C++ with it. but when i use even the most basic programs and incorporate the cin keyword, and run the program, I dont get an oppurtunity to put in anything during runtime and sometimes it inserts random values by itself! for example, if i ran this in textmate:
#include <iostream>
int stonetolb(int);
int main() {
using namespace std;
int stone;
cout << "enter the weight in stone";
cin >> stone;
int pounds = stonetolb(stone);
cout << stone << "stone = ";
cout << pounds <<" pounds.";
return 0;
}
int stonetolb(int sts) {
return 14 * sts;
}
I would come out with the output:
enter the weight in stone32767stone = 458738 pounds.
Why is this happening, and how do I stop it?
Most likely, the input statement cin >> stone is failing, and stone has an undefined value. You need to check for input failure by using if (cin >> stone) { ... } else { // input failure }. As for why such a simple program would exhibit failing behaviour, I don't know- you would have to check the textmate documentation.