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();
}
Related
I am a beginner in c++ coding and i have an assignment for my class. I am trying to read the first line of integers separated by spaces 2 spaces in the file (cannot use arrays or vectors). I have seen many tutorials telling me to use getline () and simply reading each and every integer and storing it into its own variable, but neither method has been working for me. Does anybody have a way to read in the first line with a while loop and have it so that I can then find the maximum and minimum values from the line, as well as calculate the average EXCLUDING the maximum and minimum values?
sample input i was instructed to analyze is as follows
5 7 9 8 7
30032
51111
52000
42000
9 8 6 3 7
70000
23765
24000
41004
Here is what I have so far.
{
void PrintIntro (); {
cout << "*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-" <<endl;
cout << "Welcome to Tallahassee Idol! Where Stars are Born!!!" <<endl;
cout << "*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-" <<endl<<endl;
}
/*******************************************************************************/
void OpenFile (); {
ifstream myFile; // filestream for input file
string fileName; // string for user to input filename
cout <<"Enter a valid filename (no blanks please): ";
cin >> fileName;
myFile.open(fileName);
while (!myFile) {
cout << "Please re-enter a valid filename: "<<endl<<endl;
cin >> fileName;
myFile.open(fileName);
}
}
/*******************************************************************************/
void GetJudgeScore1 (); {
ifstream myFile; // filestream for input file
string fileName; // string for user to input filename
int player1Total = 0; // total score for player 1
int player1Average = 0; // average for player 1
int highScore1 = 0; // highest score to be excluded
int lowScore1 = 100; // lowest score to be excluded
const int judgeAmt = 5;
cout << "Processing Judge Data for Contestant 1" <<endl;
cout << "=====================================" <<endl;
cout << "Judge scores are: ";
if (myFile.is_open()){ // if the file is open, read data in
// here is where i ran into problems
}
}
return 0;
}
You can use a combination of std::string and std::istringstream and std::getline to iterate through the different integers in the line as shown below. The explanation is given in the comments.
#include <iostream>
#include<string>
#include <sstream>
#include <fstream>
#include <climits>
int main()
{
std::string line;//for storing a single line
int max = INT_MIN, min = INT_MAX, num = 0, count =0;
std::ifstream inFile("input.txt");
if(inFile)
{
while(std::getline(inFile, line))//go line by line
{
std::istringstream ss(line);
while(ss >> num)//go number by number
{
if(num > max)
{
max = num;//update the maximum
}
if(num < min)
{
min = num; //update the minimum
}
++count;
}
//you can add an if statement here to print the result only if count > 1
std::cout<<"max is: "<<max<<std::endl;
std::cout<<"min is: "<<min<<std::endl;
count = 0; //make the count 0 for next iteration
max = INT_MIN; //reset max
min = INT_MAX; //reset min
std::cout<<"----------------------"<<std::endl;
}
}
else
{
std::cout<<"input file cannot be opened"<<std::endl;
}
return 0;
}
The output of the above program can be seen here:
max is: 9
min is: 5
----------------------
max is: 30032
min is: 30032
----------------------
max is: 51111
min is: 51111
----------------------
max is: 52000
min is: 52000
----------------------
max is: 42000
min is: 42000
----------------------
max is: 9
min is: 3
----------------------
max is: 70000
min is: 70000
----------------------
max is: 23765
min is: 23765
----------------------
max is: 24000
min is: 24000
----------------------
max is: 41004
min is: 41004
----------------------
Method 2
By looking at your comments below, it seems you do not want(or not allowed) to use climits. The below program shows how you can find the max and min without using climits.
#include <iostream>
#include<string>
#include <sstream>
#include <fstream>
int main()
{
std::string line;//for storing a single line
std::string numWord; //for storing a single number as std::string
int max = 0, min = 0, num = 0, count =0;
std::ifstream inFile("input.txt");
if(inFile)
{
while(std::getline(inFile, line))//go line by line
{
std::istringstream ss(line);
//read the first number in max and min
ss >> max;
min = max;
while(ss >> num)//go number by number
{
if(num > max)
{
max = num;//update the maximum
}
if(num < min)
{
min = num; //update the minimum
}
++count;
}
//you can add an if statement here to print the result only if count > 1
std::cout<<"max is: "<<max<<std::endl;
std::cout<<"min is: "<<min<<std::endl;
count = 0; //make the count 0 for next iteration
max = 0; //reset max
min = 0; //reset min
std::cout<<"----------------------"<<std::endl;
}
}
else
{
std::cout<<"input file cannot be opened"<<std::endl;
}
return 0;
}
The output of the above program can be seen here.
Note
Since this is a homework problem, i am skipping finding out the average of the numbers so that you can modify the above program accordingly and so that i don't give the whole solution myself. Note that since your requirement is that not to use std::vector or arrays, i haven't used them in my program.
Hint:(for finding average) Add a variable called sum or average and add value of variable num to it inside the while loop.
I am unsure as to what you mean by "cannot use arrays or vectors." The following code will read each line and save it to a string, convert it, and add it to an integer array, for easier storage. You could use multiple variables instead.
#include <fstream>
#include <string>
void getData() {
std::string output;
int i = 0, data[10]; // Pre-defined array size, looking at your data set.
std::ifstream myFile;
myFile.open("Path\\To\\Your\\File.txt", ios::in);
while(getline(myFile, output))
{
data[i] = std::stoi(output);
i++;
std::cout << data[i] << "\n";
}
myFile.close();
}
Output:
57987
30032
51111
52000
42000
98637
70000
23765
24000
41004
Trying to create a program that takes a coffee flavor add-in and checks if it's valid using an array.
If valid it uses the array index to gather price information.
I managed to write the code below, but it only works for 1 iteration.
How can alter it so a user can enter: Cream and cinnamon and output the total of each add-in as well as the total price of the cup of coffee? The cup of coffee starts with a base price of $2.00
#include <iostream>
#include <string>
using namespace std;
int main()
{
// Declare variables.
string addIn; // Add-in ordered
const int NUM_ITEMS = 5; // Named constant
// Initialized array of add-ins
string addIns[] = { "Cream", "Cinnamon", "Chocolate", "Amaretto", "Whiskey" };
// Initialized array of add-in prices
double addInPrices[] = { .89, .25, .59, 1.50, 1.75 };
bool foundIt = false; // Flag variable
int x; // Loop control variable
double orderTotal = 2.00; // All orders start with a 2.00 charge
string QUIT = "XXX";
// Get user input
cout << "Enter coffee add-in or XXX to quit: ";
cin >> addIn;
// Write the rest of the program here.
for (x = 0; x < NUM_ITEMS && foundIt == false && addIn != QUIT; x++) {
if (addIn == addIns[x]) {
foundIt = true;
x--;
}
}
if (foundIt == true) {
cout << addIns[x] << " $" << addInPrices[x] <<endl;
cout << "$" << orderTotal + addInPrices[x] <<endl;
}
else {
cout << "Sorry, we do not carry that." <<endl;
cout << "Order total is $ " << orderTotal <<endl;
}
return 0;
}
Don't use parallel arrays - you will mess up maintaining them.
Better options:
Create a struct for your add-ins:
struct Addin {
std::string name;
double price;
}
and use an array (or better yet an std::vector) of those structs.
Another option is to use a map:
std::map<std::string, double> addIns = {
{"Cream", .89},
{"Cinnamon", .25},
// etc.
};
Then you won't need a loop, just a lookup
auto item = addIns.find(addIn);
if(item != addIns.end() {
// do your math here
}
Your program is written to get a single output. For multiple outputs there have to be loops and the not found condition also has to be re-written.
try this
#include <iostream>
#include <string>
using namespace std;
int main()
{
// Declare variables.
const int NUM_ITEMS = 5; // Named constant
string addIn[NUM_ITEMS]; // Add-in ordered
// Initialized array of add-ins
string addIns[] = { "Cream", "Cinnamon", "Chocolate", "Amaretto", "Whiskey" };
// Initialized array of add-in prices
double addInPrices[] = { .89, .25, .59, 1.50, 1.75 };
//bool foundIt = false; // Flag variable
int x, i, j; // Loop control variable
double orderTotal = 2.00; // All orders start with a 2.00 charge
string QUIT = "XXX";
// Get user input
cout << "Enter coffee add-ins followed by XXX to quit: ";
for(i=0; i<NUM_ITEMS; i++) {
cin >> addIn[i];
if(addIn[i] == QUIT) {
i++;
break;
}
}
int foundIt[i];
// Write the rest of the program here.
for(j=0; j<i; j++) {
foundIt[j] = -1;
for(x = 0; x<NUM_ITEMS && foundIt[j] == -1 && addIn[j] != QUIT; x++) {
if (addIn[j] == addIns[x]) {
foundIt[j] = x;
}
}
}
for(j=0; j<i-1; j++) {
cout << addIn[j];
if(foundIt[j] != -1) {
cout << " $" << addInPrices[foundIt[j]] << endl;
orderTotal = orderTotal + addInPrices[foundIt[j]];
}
else {
cout << " - Sorry, we do not carry that." <<endl;
}
}
cout << "$" << orderTotal <<endl;
return 0;
}
Sample Outputs
Enter coffee add-ins followed by XXX to quit: Cream Cinnamon XXX
Cream $0.89
Cinnamon $0.25
$3.14
Enter coffee add-ins followed by XXX to quit: Cream Onion XXX
Cream $0.89
Onion - Sorry, we do not carry that.
$2.89
What I did was made addIn array of srings with NUM_ITEMS size instead of variable. Also, foundIt was made an integer array to keep track of indexes where the items are found in addIns array and -1 if not found.
To only access the items that user has entered in addIn, your QUIT has been made the termination condition in that array.
The structure you are looking for is a while or do/while loop.
To be able to enter "empty" lines use std::getline from.
The structure of your program will then look something like this :
As you can see I have a habit of changing my boolean expressions into functions (predicates). This makes code more readable and predicates reusable in other bits of code.
#include <iostream>
#include <string>
bool is_quit(const std::string& input)
{
return input.length() > 0;
}
bool is_valid_input(const std::string& input)
{
return true; // your own check
}
int main()
{
bool quit = false;
std::string input;
do
{
std::cout << "give input : ";
std::getline(std::cin, input);
quit = is_quit(input);
if (is_valid_input(input) && !quit)
{
std::cout << "ok" << std::endl;
}
} while (!quit);
return 0;
}
I want to print out struct variable which is customer name and total price from a file.txt using dev c++, but the screen prints out no result. The screen is blank but no error occured.
This is the content of the file
File name :Fruit Order.txt
Jean;1;Apple;1;1;
Alex;2;Apple;Kiwi;1;1;1;2;
Adam;2;Kiwi;Watermelon;2;1;2;5;
This the coding
#include<iostream>
#include<fstream>
using namespace std;
struct CustInfo{
string custName;
int order;
double totalPrice;
};
struct OrderInfo{
string fruitName;
int quantity;
double price;
};
int main(){
int x = 0, y = 0;
double temp = 0;
CustInfo CI[3];
ifstream file1;
file1.open("Fruit Order.txt");
while(!file1.eof()){
for(x; x < 3; x++){
getline(file1, CI[x].custName, ';');
file1 >> CI[x].order;
file1.ignore(1, ';');
OrderInfo OI[CI[x].order];
for(y; y < CI[x].order; y++){
getline(file1, OI[y].fruitName, ';');
file1 >> OI[y].quantity;
file1.ignore(1, ';');
file1 >> OI[y].price;
file1.ignore(1, ';');
temp += (OI[y].quantity * OI[y].price);
}
CI[x].totalPrice = temp;
temp = 0;
}
}
for(x = 0; x < 3; x++){
cout << CI[x].custName << endl;
cout << CI[x].totalPrice << endl;
}
file1.close();
return 0;
}
Here I put some changes to your code with //----> before them
#include<iostream>
#include<fstream>
using namespace std;
struct CustInfo{
string custName;
int order;
double totalPrice;
};
struct OrderInfo{
string fruitName;
int quantity;
double price;
};
int main(){
int x = 0, y = 0;
double temp = 0;
CustInfo CI[3];
ifstream file1;
file1.open("Fruit Order.txt");
// ---> dummyString to read unwanted strings ... you can use it to read unwanted ; but I use it for \n
string dummyString;
//-----> removed while ( user4581301 recommendation )
// while(!file1.eof()){
for(x; x < 3; x++){
getline(file1, CI[x].custName, ';');
file1 >> CI[x].order;
file1.ignore(1, ';');
// OrderInfo OI[CI[x].order];
//------> added this (dynamic allocation as order is known only at runtime)
OrderInfo* OI = new OrderInfo[CI[x].order];
for(y; y < CI[x].order; y++){
getline(file1, OI[y].fruitName, ';');
}
// split the two loops because all fruitNames come before other numbers. So, read all fruitNames first
for (y = 0; y < CI[x].order; y++)
{
file1 >> OI[y].quantity;
file1.ignore(1, ';');
file1 >> OI[y].price;
file1.ignore(1, ';');
temp += (OI[y].quantity * OI[y].price);
}
CI[x].totalPrice = temp;
temp = 0;
// --------> added this | or make it local (inside for loop)
// -- this is because you access OI[y] and its size is 3 while y increases and is outside for(x...)
y= 0;
// ---> deleted OI because we don't need it
delete[] OI;
// ----> if you delete this, the custName string will have \n character in it (new line)
getline(file1,dummyString,'\n');
}
for(x = 0; x < 3; x++){
cout << CI[x].custName << endl;
cout << CI[x].totalPrice << endl;
}
file1.close();
return 0;
}
To be honest. There are many problems in your code. Biggest issue is that you have 0 lines of comments in your code. With that it is only hardly readable.
Then, the input data has a clumsy format, which makes it hard to read. Basically, quantities and price should follow immediately after then product name, and better put in a separate line. Anyway. It is like ist is.
So, and then you have dynamic data, That means, you do not know in advance, how big your arrays will must be. In the below example I use new and raw pointers for owned memory. This you should normally never do and use always a std::vector instead. But ok, lets see.
The data model, so, how and with with structure you want to model the data is also and always essential. Please see my approch in the example below.
The additional difficulty while parsing the input line is the change between formatted and unformatted input. Special care must be taken to handle the semicolon correctly.
Then, you would add member functions in your structs to handle the work. Objects should be encapsulated.
All this I will not do in the below example solution. I stick more or less to your programming style, but add a lot of comments.
Please see:
#include <iostream>
#include <fstream>
#include <string>
struct Product{
std::string productName{};
unsigned int quantity{};
double price{};
double totalPriceProduct{};
};
struct Order {
std::string customerName{};
Product *products{};
unsigned int numberOfProducts;
double totalPriceOrder{};
};
struct OrderDatabase {
Order* orders{};
unsigned int numberOfOrders{};
double totalPrice;
};
int main() {
// Here we will store all our orders
OrderDatabase orderDatabase{};
// Open the source file
std::ifstream fileStream{ "r:\\Fruit Order.txt" };
// Count, how many orders we do have in the file
std::string lineWithOrder{};
// Read all lines from file an throw content away. Count the lines
while (std::getline(fileStream, lineWithOrder) and not lineWithOrder.empty())
++orderDatabase.numberOfOrders;
// Reset stream. Clear eof bit and reset file pointer
fileStream.clear();
fileStream.seekg(0, std::ios::beg); // back to the start!
// Now dynamically allocate memory for our orders
orderDatabase.orders = new Order[orderDatabase.numberOfOrders];
char dummy; // for reading the semicolon and throw it away
// Read all data
unsigned int orderIndex{};
// -----------------------------------------------------------------------------------------------------------
// Read all data
do {
// Read customer name
std::getline(fileStream, orderDatabase.orders[orderIndex].customerName, ';');
// How many products are in this order?
fileStream >> orderDatabase.orders[orderIndex].numberOfProducts >> dummy;
// Allocate memory for new products
orderDatabase.orders[orderIndex].products = new Product[orderDatabase.orders[orderIndex].numberOfProducts];
// Read product names
for (unsigned int productIndex = 0; productIndex < orderDatabase.orders[orderIndex].numberOfProducts; ++productIndex) {
std::getline(fileStream, orderDatabase.orders[orderIndex].products[productIndex].productName, ';');
}
// Read product quantity and price
for (unsigned int productIndex = 0; productIndex < orderDatabase.orders[orderIndex].numberOfProducts; ++productIndex) {
fileStream >> orderDatabase.orders[orderIndex].products[productIndex].quantity >> dummy;
fileStream >> orderDatabase.orders[orderIndex].products[productIndex].price >> dummy;
// Calculate total price for product
orderDatabase.orders[orderIndex].products[productIndex].totalPriceProduct = orderDatabase.orders[orderIndex].products[productIndex].quantity * orderDatabase.orders[orderIndex].products[productIndex].price;
// Accumulate prices in oder
orderDatabase.orders[orderIndex].totalPriceOrder += orderDatabase.orders[orderIndex].products[productIndex].totalPriceProduct;
// Accumulate overall total price
orderDatabase.totalPrice += orderDatabase.orders[orderIndex].products[productIndex].totalPriceProduct;;
}
// Read next line
++orderIndex;
} while (fileStream and orderIndex < orderDatabase.numberOfOrders);
// -------------------------------------------------------------------------------------------------------
// Show result to user
std::cout << "\n\nThere are " << orderDatabase.numberOfOrders << " orders in the database. Details:\n";
for (orderIndex = 0; orderIndex < orderDatabase.numberOfOrders; ++orderIndex) {
// Show one order
std::cout << "\nOrder number " << orderIndex + 1 << " for Customer: " << orderDatabase.orders[orderIndex].customerName << " with " << orderDatabase.orders[orderIndex].numberOfProducts << " products\n";
// Show product in this order
for (unsigned int productIndex = 0; productIndex < orderDatabase.orders[orderIndex].numberOfProducts; ++productIndex) {
std::cout << "Product: " << orderDatabase.orders[orderIndex].products[productIndex].productName << " \t Quantity: " << orderDatabase.orders[orderIndex].products[productIndex].quantity << " \tPrice: " <<
orderDatabase.orders[orderIndex].products[productIndex].price << " \t Total --> " << orderDatabase.orders[orderIndex].products[productIndex].totalPriceProduct << '\n';
}
// Show total order price
std::cout << "\nTotal price of this order: " << orderDatabase.orders[orderIndex].totalPriceOrder << '\n';
}
// Show overall total
std::cout << "\n\nTotal price overall: " << orderDatabase.totalPrice << '\n';
// Free memory
for (orderIndex = 0; orderIndex < orderDatabase.numberOfOrders; ++orderIndex) {
delete[] orderDatabase.orders[orderIndex].products;
}
delete[] orderDatabase.orders;
return 0;
}
As said. I would not do it that way, but use more advance C++ techniques.
But please try this in the beginning.
I am new to programming, so I have what is probably a basic question. I currently have a text file with 365 lines...one line per day of the year. These are the first four lines of the file:
2003 1 1 18 0 -1 36 50 46
2003 1 2 16 3 -1 43 56 52
2003 1 3 19 7 -1 42 56 49
2003 1 4 14 3 -1 42 58 50
I eventually have to graph these using a special library given to us, but first I want to put the data for each column into an array. This is the part of my code where I attempt to do just that.
#include "library.h"
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
ifstream in;
int yr[364], mo[364], day[364], windSpeed[364], precip[364], snowDepth[364], minTemp[364], maxTemp[364], avgTemp[364];
void main() {
make_window(800, 800);
set_pen_color(color::red);
set_pen_width(8);
// open file, read in data
in.open("PORTLAND-OR.TXT");
if (in.is_open()) {
// read each column into an array
for (int i = 0; i < 364; i++) {
in >> yr[i] >> mo[i] >> day[i] >> windSpeed[i] >> precip[i] >> snowDepth[i] >> minTemp[i] >> maxTemp[i] >> avgTemp[i];
cout << mo[i] << " " << day[i] << endl;
}
in.close();
}
else {
cout << "error reading file" << endl;
exit(1);
}
}
When I attempt to print out all of the values in the second and third columns (month and day), it begins printing from march 8 (3 8) through december 31 (12 31). I need it to print all the way from January 1 to December 31. Is there a reason why the first two months worth of values isn't printing?
Below is a really stupid main-only program that reads your file in with your existing reading code and prints it back out again. I've embedded a running commentary in the code with things you should consider doing.
Basically, this is whaty I was talking about yesterday in loop not displaying all data entries from file
#include <iostream>
#include <fstream>
using namespace std; // bad! Avoid doing this in real life.
int yr[364],
mo[364],
day[364],
windSpeed[364],
precip[364],
snowDepth[364],
minTemp[364],
maxTemp[364],
avgTemp[364]; // bad! define a structure instead
/* Example:
struct stats
{
int yr;
int mo;
int day;
int windSpeed;
int precip;
int snowDepth;
int minTemp;
int maxTemp;
int avgTemp;
};
struct stats statistics[364]; // bad! use a std::vector instead
std::vector<stats> statistics;
*/
int main()
{
// removed all the windowing stuff.
ifstream in;
in.open("PORTLAND-OR.TXT");
if (in.is_open())
{
// read each column into an array
for (int i = 0; i < 364; i++)
{ // what do you do if the file ends early or contains bad information?
in >> yr[i] >>
mo[i] >>
day[i] >>
windSpeed[i] >>
precip[i] >>
snowDepth[i] >>
minTemp[i] >>
maxTemp[i] >>
avgTemp[i];
}
in.close();
}
else
{
cout << "error reading file" << endl;
return 1;
}
// printing out all the stuff that was read
for (int i = 0; i < 364; i++)
{
cout << yr[i] << "," <<
mo[i] << "," <<
day[i] << "," <<
windSpeed[i] << "," <<
precip[i] << "," <<
snowDepth[i] << "," <<
minTemp[i] << "," <<
maxTemp[i] << "," <<
avgTemp[i] << endl;
}
}
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 +