displaying the country with the smallest area from a file in C++ - c++

my task is to write a program to read a file called countries.txt which contains a number of countries and their respective land areas and then display the country with the largest and smallest land areas. I am having trouble displaying the country with the smallest land area and would be more then grateful if someone is able to show me how to do it.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream ins; // declare an input file stream object
ins.open("/Users/daneided/Desktop/countries.txt"); // open the file by pasting the path
if (ins.fail()) { // program to check if the file failed to open
cout << "Error opening file";
return -1;
}
string biggestCountry; // name of the biggest country
int biggestArea = 0; // the country with the biggest area
for (int i = 0; i < 5; i++) { // read five lines from the file
string countryName;
int area;
ins >> countryName >> area; // read 2 variables from the stream line
if (area > biggestArea) { // update the current maximum if greater
biggestArea = area;
biggestCountry = countryName;
}
}
ins.close(); // close the file
cout << "Biggest country is: " << biggestCountry <<
" (" << biggestArea << ") " << endl;
return 0;
}

Try adding this belkow your if for the biggest country, you should get the hang of it from here:
int smallestArea = biggestArea; /* because you need a default value that is greater then the minimum area of the smallest country */
if (area < smallestArea) {
smallestArea = area;
smallestCountry = countryName;
}

Related

File not opening a second time in c++

My code is split into task 1 and task 2. I want to open and close with each task to reset the pointer to the start position. I did try fseek(OH-in.txt, 0, SEEK_SET) instead of opening a second time but that didn't work.
The tasks don't matter just pay attention to where I open and close the file OH-in.txt.
The file only opens (and outputs data that was read) for the first task!
Here is my code
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
string collegeName;
string location;
int currentEnroll;
int tuition;
int numOfSchools = 0; // edit this in code below
/*
TASK 1
*/
// TASK 1: list the schools and the tuition of the schools in Cincinnati with
// tuition below 20,000
ifstream file;
file.open("OH-in.txt");
vector<string> arr; // declare array
// read lines of OH-in.txt
while (file >> collegeName >> location >> currentEnroll >> tuition) {
// add collegeName and location to array if true
if (tuition < 20000 && location == "Cincinnati") {
collegeName = "(" + collegeName + " $" + to_string(tuition) + ") ";
arr.push_back(collegeName);
numOfSchools++;
}
}
for (int i = arr.size() - 1; i >= 0; i--) {
cout << arr[i];
}
cout << numOfSchools << " schools meet this criteria.";
file.close();
/*
TASK 2
*/
// TASK 2 Calculate and display the average tuition of schools with more than
file.open("OH-in.txt");
vector<string> arr2;
double avgTuition = 0;
int expensiveSchools = 0;
// iterate through the list. If a school with enrollment higher than 10,000 is found, add tuition to total. It will later be divided by the total number of expensive schools.
while (file >> collegeName >> location >> currentEnroll >> tuition) {
if (currentEnroll > 10000) {
avgTuition += tuition;
expensiveSchools += 1;
}
if (collegeName == "BGSU") {
cout << "BGSU Tuition: " << tuition << endl;
}
}
file.close();
}

Calculate average number from char array

Im trying to calculate the average out of a couple of number inside an char array. The reason for this is that i imported data from a text document and i made it read only every 2nd line to get the numbers that i wanted.
Now i need to get the average out of these numbers but i cant make it work. I'm starting to get mad about this and i feel that the solution would be rather simple.
EDIT:
The file consists of names and numbers. I.e:
Jason Smith
32
Mary Jane
52
Stevie Wonder
68
Micheal Jackson
59
#include <fstream>
#include <iostream>
using namespace std;
double averageNum(char array[], int size) { // A function to calculate the average number
int sum = 0;
double avg;
for(int i=0; i<size; i++){
array[i]+= sum;
}
avg = sum / size;
return avg;
}
int main(){
char age [50][30];
double avg;
int rows = 0;
ifstream elevInfo("elevinfo.txt"); // Opens a stream to get data from the document
if (! elevInfo){ // Error message if the file couldn't be found
cout << "Could not find the file elevinfo.txt" << endl;
return (1);
}
while(elevInfo.getline(age[rows/2], 30)){ // Reading every 2nd line to an array
rows++;
}
avg = averageNum(age[], rows); // Function call with the numbers from the array and the variable rows as a pointer
cout << "Average age equals: " << avg << endl;
}
this is one of many possible solutions for your problem:
int main()
{
// Opens a stream to get data from the document
ifstream elevInfo("elevinfo.txt");
// Error message if the file couldn't be found
if (!elevInfo)
{
cout << "Could not find the file elevinfo.txt" << endl;
return (1);
}
int sum = 0;
int lineCounter = 0;
// loop till end of file
while (!elevInfo.eof())
{
// prepare buffer
char line[30];
// read line into buffer
elevInfo.getline(line, 30);
// do this every second line
if (lineCounter % 2 == 1)
{
// get age as int using function atoi()
int age = atoi(line);
// increase sum by the current age
sum += age;
}
// increment line-counter
lineCounter++;
}
// calculate the average
// divide lineCounter by 2 because only every second line in your file contains an age
double avg = sum / (lineCounter / 2.0);
cout << "Average age equals: " << avg << endl;
return 0;
}
As you can see it also doesn't need the function averageNum.

How would I make program subtract the previous temp and current temp

An interactive C++ program whose input is a series of 12 temperatures from the user. It should write out on file tempdata.dat each temperature as well as the difference between the current temperature and the one preceding it. The difference is not output for the first temperature that is input. At the end of the program, the average temperature should be displayed for the user via cout.
Here is What I have so far:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int counter = 0;
int previousTemp;
ofstream file; //declares a file of type ofstream
file.open("temperaturefile.txt"); //opens the file with open method
int temperature = 0;
int difference = 0;
cout << "Enter 12 temperatutes" << endl;
file << temperature;
while (counter < 12)
{
cin >> temperature;
counter++;
// difference = temperature-previousTemp;
// cout << difference << endl;
//
}
}
You have it commented in your code? I don't understand
difference = temperature-previousTemp;
You can keep track of previousTemp at the end of your loop.
After everything in the loop put
previousTemp=temperature;

Unhandled Memory Exception

I'm working on a program that reads a set of data based on patient's ID numbers and their blood pressure readings. The program will then add all the readings together and come up with an average. It'll then display that average. This is my program so far:
#include <iostream>
#include <string>
#include <conio.h>
#include <fstream>
using namespace std;
int main()
{
//Initialize Required Variables For Program
int patientCount;
string id;
string rHowMany; //String To Read From File
int howMany;
int howManyCount;
int avg = 0;
int avg2;
string line;
int number_lines = 0;
ifstream reader ("data.txt"); //Open The Data File To Be Read From
patientCount = 0;
while (getline(reader, line))
{
number_lines += 1;
}
//getline(reader, id); //Get the patients ID
//getline(reader, rHowMany); //Get How Many BP Records The Patient Has
for (number_lines; number_lines > 0; number_lines--)
{
reader >> id;
reader >> rHowMany;
howMany = stoi(rHowMany);
howManyCount = howMany;
patientCount += 1;
cout << "Patient ID: " + id;
for (howManyCount; howManyCount > 0; howManyCount--)
{
reader >> avg2;
avg = avg + avg2;
}
}
cout << avg;
cout << "\n";
cout << howMany;
avg = avg / howMany;
cout << "\n";
cout << avg;
_getch();
return 0;
}
When I run the program I get this error:
Unhandled exception at at 0x756DB727 in Blood Pressure.exe: Microsoft C++ exception: std::invalid_argument at memory location 0x0042F794.
I'm not quite sure what that means, but it opens up a list of code I've never seen before. Like I said I'm not sure why it's throwing this error, or what the error means, but if someone could help me, I would appreciate it.
This line:
cout << "Patient ID: " + id;
Is flawed. You are trying to append id to "Patient ID: ", but that is not what is happening.
The string literal "Patient ID: " is actually a pointer to a sequence of characters (that is, an array). When you use the plus sign, you are performing pointer arithmetic between the memory address of the character sequence and id. If id is larger than the length of the string, this will probably lead to your program trying to access an invalid location.
To fix this, simply print id after the sequence by making two separate calls to the << operator:
cout << "Patient ID: " << id; // no +

Use ifstream to read a text file with random generated numbers in columns and find the minimum and maximum from the list?

I am creating a school project but seems lost at the moment. Can someone help me figure out my problem? Here's what's going on:
I have a program that outputs a random generated numbers in a text file using ofstream. It is generated with a format of two columns (one column is SalePrice & the second column RegularPrice). My problem is creating a code that will do the following:
Create a function that will read the text file generated by the first program
Find the average of the second column ONLY! (Regular Price) then outputs it in the screen
Find the minimum and maximum of the second column ONLY! (Regular Price) then outputs it in the screen
Please help! I need help how to code the ifstream part, I am new to C++ and have tried all the solutions in many books but doesn't seem to work for my needs? :-( Any help will be greatly appreciated! Thanks in advance!
Here's just the section of my code (not the entirety), it is not giving me an error . . . it is simply not giving me anything:
float SalePrice[userInput];
float RegularPrice;
string cPrice;
string readFile;
int count = 0;
ifstream inputFile;
inputFile.open(fileName);
inputFile >> RegularPrice;
// To get you all the lines and place the line from myfile into the line variable
while(!inputFile.eof() && getline(inputFile, readFile))
{
if (count < userInput)
{
inputFile >> readFile;
readFile += cPrice; // Saves the line in STRING.
//display the line we gathered:
cout << cPrice << endl;
}
++count;
}
avgRPrice = RegularPrice / userInput;
cout << endl;
cout << fixed << setprecision (2);
cout << "The average of all the Regular Prices in the file is: " << avgRPrice << endl;
cout << "The minimum Regular Price in the file is: " << minRPrice << endl;
cout << "The maximum Regular Price in the file is: " << maxRPrice << endl;
EDITED:
Here's my current code for finding the max & min:
int maxRPrice(float RPrice[])
{
if (RPrice > maxRPrice)
maxRPrice = RPrice;
return maxRPrice;
}
int minRPrice(float RPrice[])
{
if (RPrice < minRPrice)
minRPrice = RPrice;
return minRPrice;
}
Here is an improved version of your code which works perfectly for me:
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
const int userInput = 2;
float SalePrice[userInput]; //Make an array
float RegularPrice[userInput]; //Make an array
string readFile;
ifstream inputFile;
inputFile.open("yourFile.txt");
if(!inputFile){ //Check wether the file is open
cout<<"Couldn't open file!" << endl;
return -1;
}
// To get you all the lines and place the line from myfile into the line variable
for(int count = 0; !inputFile.eof() && (count < userInput) ; ++count) //Why are you using a while-loop if you need to count the iterations
{
//
inputFile >> SalePrice[count] >> RegularPrice[count]; //loads column SalePrice/RegularPrice into the array at position 'count'
}
float sumRegularPrice = 0;
for(int i=0; i < userInput; i++)
sumRegularPrice += RegularPrice[i];
float avgRPrice = sumRegularPrice / userInput;
cout << endl;
cout << fixed;
cout << "The average of all the Regular Prices in the file is: " << avgRPrice << endl;
//cout << "The minimum Regular Price in the file is: " << minRPrice << endl;
//cout << "The maximum Regular Price in the file is: " << maxRPrice << endl;
system("pause");
return 0;
}
Why are you loading RegularPrice only once? As far as I got your explanation about the file format (you said one column is SalePrice & the second column RegularPrice), every line might have this content:
3.44 5.99
To get the min and max price you can simply write two functions.
With this input:
3.44 5.99
5.54 8.99
I get this output (in the console):
The average of all the Regular Prices in the file is: 7.490000
If you have some questions don't hesitate to ask me.