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 +
Related
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();
}
C++ Code
Basically i am trying to take input from a file and store the data in variables, But i am unable to do that because each time i compile this code it compiles successfully but gives a runtime error.(Right Now i have just Data of 3 Students, so i set the condition to run the loop 3 times).
The variable "Name" will get the name from the file, "sap" will get the roll number, "number" will get the number of subjects the user wants to enter marks of (Max 5), and "marks" will enter marks of those subjects.
Variables "SapFile", "NumberFile", and "MarksFile" will get the string data from the file and store them in their respective format variables as mentioned above.
What it does Exactly is read Data from the file to the variables and also prints them, But when it reaches at "i=3" Then instead of this condition becoming false and terminating the Loop and exiting the Function, it gives a runtime error. [Note: It prints the data of 3 students in the file correctly and then gives Runtime error].
The Error Snap is Attaches as follows,
Runtime Error Image
'''
This is My code
void read_in_variables(void)
{
string SapFile = "";
string NumberFile = "";
string MarksFile = "";
int studentCount = 0;
struct Student
{
string Name = "";
int sap = 0;
int number = 0;
int marks[5] = { 0 };
};
Student S[50];
ifstream outFile;
outFile.open("Students.csv", ios::in);
if (outFile.is_open())
{
for (int i = 0; i<3; i++)
{
if (i == 0)
cin.ignore();
getline(outFile, S[i].Name, ',');
studentCount++;
getline(outFile, SapFile, ',');
S[i].sap = stoi(SapFile);
getline(outFile, NumberFile, ',');
S[i].number = stoi(NumberFile);
cout << i + 1 << ". " << S[i].Name << ", " << S[i].sap << ", " << S[i].number;
for (int j = 0; j < (S[i].number - 1); j++)
{
getline(outFile, MarksFile, ',');
S[i].marks[j] = stoi(MarksFile);
cout << ", " << S[i].marks[j];
}
getline(outFile, MarksFile, '\n');
S[i].marks[S[i].number] = stoi(MarksFile);
cout << ", " << S[i].marks[S[i].number];
cout << endl;
}
outFile.close();
if (studentCount == 0)
cout << "\n\nNo Student Records Present.\n\a\n";
}
else
{
cout << "File not Opened !!! ";
}
}
Moreover, when at first i tried to put "outFile.eof()" in the condition statement then it returns false in the beginning and does not even enters in the loop, and Prints "No Student Records Present." as "StudentCount" has Value 0.
[I have included All the Header Files necessary for this function].
Kindly Help me Solve this issue and make this function work perfectly.
I am very new to c++ and currently trying to complete a few little challenges to get up to speed with the simpler aspects.
I'm trying to create an array (found info to suggest vectors are the same and better) of structs to hold data about 10 people. Each person has an "index" (to identify person1, person2, person3, etc..), a "num" (to store the collected data) and a "rank" (a variable which I intend to use to sort the people using the data collected)
The code doesn't show any errors before compiling, however, when the first piece of data is entered I get the following message:
"Debug Assertion Failed!
Program: C:\WINDOWS\SYSTEM32\MSVCP140D.dll
File: d:\program files\microsoft visual studio\community\vc\tools\msvc\14.12.25827\include\vector
Line: 1795
Expression: vector subscript out of range"
I have tried searching through multiple threads but I can't seem to work out why this problem is occurring.
My code:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct person
{
int index; /*person number*/
int num; /*number of pancakes eaten*/
int rank; /*rank used for sorting people*/
};
vector<person> people; /*create a vector (array) of "person"'s*/
void getData()
{
cout << "You will be asked to enter data from 10 different people" << endl;
cout << "\n" << "The question is; 'How many pancakes did they eat for breakfast?'" << endl;
cin.get();
for (int i = 1; i <= 10; i++)
{
system("CLS");
int j;
cout << "Person " << i << " : ";
cin >> j;
person temp;
people.push_back(temp);
people[i].index = i;
people[i].num = j;
people[i].rank = i;
}
}
int main()
{
getData(); /*collect data for the people*/
system("CLS");
cout << "Data Collected : " << endl;
system("pause");
}
Thanks in advance for anyone who can help.
The problem is in your indexing. The index starts at 0 and not 1. So what happens is when you push the first element, it is stored at people[0]. Then you try to access people[1], since i = 1. Hence the subscript is out of range error.
You need to modify the code to be:
....
for (int i = 0; i < 10; i++)
{
system("CLS");
int j;
cout << "Person " << i << " : ";
cin >> j;
person temp;
people.push_back(temp);
people[i].index = i;
people[i].num = j;
people[i].rank = i;
}
....
I tried looking at the other problems people were having that were along this line but i couldn't relate them to my program. This is probably very simple but I rarely if ever do anything C++ related so I am very confused. I try and run my program which and it works up until the point were I try to use "std::cout" to display the reversed name. The program runs for a bit in the command window but eventually a window's window pops up proclaiming there was a problem and that it will end the program. I have tried to break everything down so that it is simple as it can be yet I cannot for the life of me find what's wrong. Could anyone help? I apologize for anything I have done wrong in advance and apologies for bypassing the 'problem' title filter. Cheers!
#include <iostream>
#include <string.h>
std::string firstName;
std::string lastName;
std::string fullname;
std::string reverseName;
int x;
int Simplifier;
int willThisWork;
int main()
{
std::cout << "Welcome to this random program that serves \n";
std::cout << " NO PURPOSE! \n";
std::cout << "That being said, what is your first name? : ";
std::cin >> firstName;
std::cin.ignore();
std::cout << "Okay... Now what is your last name? : ";
std::cin >> lastName;
std::cin.ignore();
fullname = firstName + " " + lastName;
std::cout << "Your full name is : " << fullname;
nameLength = fullname.length();
for(x = 0; x <= nameLength; x++)
{
Simplifier = nameLength - x;
reverseName[x] = fullname[Simplifier];
}
std::cout << "Reversed name : " << reverseName;
return 0;
}
You have to include <string> (the C++ header) instead of <string.h> (the C header).
nameLength is undeclared – has to be int nameLength.
Lastly,
Simplifier = nameLength - x;
reverseName[x] = fullname[Simplifier];
tries for x==0 to access the one past the last element of fullname. Remember, indices go from 0 to N-1, where N is the number of elements in the array/vector/string.
Edit: And you have to adjust the for loop: x < nameLength instead of x <= nameLength.
reverseName is an empty string, but you try to access its elements with reverseName[x]. Use reverseName.push_back() or reverseName += instead.
Maybe add the odd \n to format your output.
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.