Assertion failure when reading from a map - c++

int main(){
//Date Variables
int day;
int month;
int year;
string comName;
string temp;
string temp2;
//Time Variables
int hours;
int minutes;
int seconds;
string amPm;
ofstream ofstr("output.csv");
float price = 0.00;
int volume;
float value = 0.00;
float runningVol = 0.00;
float runningVal = 0.00;
float runningPrice = 0.00;
string condition;
string fileName;
string tempCName;
string compDate;
ifstream inFile;
ifstream compFile;
ifstream mainFile;
map<string, Vector <Share>> stlMap;
inFile.open("code_index.txt");
if(inFile.is_open()){
while(!inFile.eof()){
getline(inFile,tempCName);
cout << "read next line in code_index" << endl;
comName = tempCName+"\\sales_index.txt";
cout << "Company name to open is: " << comName << endl;
compFile.open(comName);
if(compFile.is_open()){
while(!compFile.eof()){
getline(compFile,fileName);
cout << "Read the fileName: " << fileName << endl;
fileName = tempCName+"\\"+fileName;
mainFile.open(fileName);
if(mainFile.is_open()){
Vector <Share> myVec;
while(!mainFile.eof()){
compDate = "";
cout << "Stored all the variables" << endl;
//Getting and storing the Date
getline(mainFile,temp2,'/');
day = atoi(temp2.c_str());
getline(mainFile,temp2,'/');
month = atoi(temp2.c_str());
getline(mainFile,temp2,' ');
year = atoi(temp2.c_str());
//cout << "date = " << day << "mo = " << month << "yr = " << year;
//Date d;
Date d(day,month,year); //Sending them to the Date class using the parameterized constructor
compDate = tempCName + "_" + d.returnDate();
//cout << "Date is: "<< compDate << endl;
cout << compDate << endl;
// Getting and storing the time variable
getline(mainFile,temp2,':');
hours = atoi(temp2.c_str());
getline(mainFile,temp2,':');
minutes = atoi(temp2.c_str());
getline(mainFile,temp2, ' ');
seconds = atoi(temp2.c_str());
getline(mainFile,temp2,',');
amPm = temp2;
//Time t;
Time t(hours,minutes,seconds,amPm);
//cout << "Hours = " << hours << "minutes = " << minutes << "seconds = " << seconds << " " << amPm;
getline(mainFile,temp2,',');
price = atof(temp2.c_str());
//cout << price;
getline(mainFile,temp2,',');
volume = atoi(temp2.c_str());
getline(mainFile,temp2,',');
value = atof(temp2.c_str());
getline(mainFile,temp2,'\n');
condition = temp2;
Share s(price,volume,value,d,t);
myVec.push_back(s);
}
stlMap[compDate] = myVec;
mainFile.close();
}
else{ cout << "Specified day file not found";}
}
compFile.close();
}
else{cout << "Specified company folder not found / sales_indexfile not found" << endl;}
}
inFile.close();
}
else
{cout << "code_index.txt not found. Please make sure the file exists";}
for(map<string, Vector <Share>>::iterator itr = stlMap.begin();itr!=stlMap.end() ;itr++ )
{
cout << "map values\n";
//cout << itr->first << endl;
//cout << itr->second.length() << endl;
}
int iii = 0;
cin >> iii;
return 0;
}
I have my own templated vector, but this for loop to print from the map causes an assertion error, help please?
Also, if I comment out the bit where I enter into the map, the error is gone.
which makes me say, the vector isnt the cause of the issue.

Related

C++: Exception thrown: Read access violation by array

I have an if statement that whenever I implement it, it throws a "read access violation" exception, even though all my other if-statements look pretty similar and work. Everything else works perfectly, so it perplexes me as to why this is happening.
if (records[i].studentArray[j].id == records[i-1].studentArray[j].id) //these two
records[i].retained++;
Full function
void readFile()
{
//Function reads the file and displays all results
int i = 0;
int j = 0;
int count;
Semester records[25]; //only holds up to 25 semesters
Student studentArray;
string semesterName;
ifstream roster;
roster.open ("records.txt");
if (roster.is_open())
{
roster >> semesterName;
while(!roster.eof())
{
roster >> count;
records[i].semesterName = semesterName;
cout << semesterName;
records[i].numStudents = count;
records[i].studentArray = new Student[count];
for (j = 0; j < count; j++)
{
roster >> records[i].studentArray[j];
if (records[i].studentArray[j].year == "FY")
records[i].fycount++;
else if (records[i].studentArray[j].year == "SO")
records[i].socount++;
else if (records[i].studentArray[j].year == "JR")
records[i].jrcount++;
else if (records[i].studentArray[j].year == "SR")
records[i].srcount++;
if (records[i].studentArray[j].id == records[i-1].studentArray[j].id)
records[i].retained++;
}
cout << endl;
cout << "FY: " << records[i].fycount << endl;
cout << "SO: " << records[i].socount << endl;
cout << "JR: " << records[i].jrcount << endl;
cout << "SR: " << records[i].srcount << endl;
cout << "FY gain/loss: " << records[i].fycount - records[i - 1].fycount << endl;
cout << "SO gain/loss: " << records[i].socount - records[i - 1].socount << endl;
cout << "JR gain/loss: " << records[i].jrcount - records[i - 1].jrcount << endl;
cout << "SR gain/loss: " << records[i].srcount - records[i - 1].srcount << endl;
cout << "Percentage gained/lost: " << static_cast<double>(records[i].numStudents - records[i - 1].numStudents) / records[i - 1].numStudents * MULTIPLIER << "%" << endl;
cout << "Number of students retained: " << records[i].retained << endl;
cout << endl;
delete[] records[i].studentArray;
roster >> semesterName;
i++;
}
roster.close();
}
else
cout << "Error: File not found" << endl;
}
Student and semester classes in the .h files
struct Semester
{
string semesterName;
int numStudents;
int fycount = 0;
int socount = 0;
int jrcount = 0;
int srcount = 0;
int retained = 0;
Student *studentArray;
};
class Student
{
public:
string id;
string year;
string name;
string lastName;
friend istream & operator>> (istream &in, Student &s);
};
Thank you!
Do a trace of your application. You will see that i is set to 0 initially and hence -1th location will be invalid in an array.
if (records[i].studentArray[j].id == records[i-1].studentArray[j].id)
That's the source of the error. Better change it to:
if (i > 0 && records[i].studentArray[j].id == records[i-1].studentArray[j].id)
Hope this helps.

I keep getting this error for the this code incompatible type of assignment of const char to std::string

if(gamble == "You Get A Raise"){
int raise[] {1,2,3,4,5,6,7,8,9,10}
cout << "You get a " raise[rand()%10] << " $ Raise" << endl;
salary = salary + raise;
}
Im trying to make a program that picks out a number 1-10 then adds that to your current salary
You actually to store the index of the raise: rand()%10 in order to display and then apply the same raise to the salary.
int raise[] {1,2,3,4,5,6,7,8,9,10};
int raiseIdx = rand()%10;
cout << "You get a " << raise[raiseIdx] << " $ Raise" << endl;
salary = salary + raise[raiseIdx];
Your gamble variable should be a std::string:
std::string gamble = "You Get A Raise";
You forgot a <<?
Try this:
int raise[] = {1,2,3,4,5,6,7,8,9,10};
int raise_value = rand()%10;
cout << "You get a " << raise[raise_value] << " $ Raise" << endl;
salary += raise[raise_value];
Your string gamble needs to be std::string too:
std::string gamble = "You Get A Raise";
Here is a full example:
int salary = 1000;
std::string gamble = "You Get A Raise";
int raise[] = {1,2,3,4,5,6,7,8,9,10};
if (std::strcmp(gamble.c_str(),"You Get A Raise") == 0) {
// or
// if (gamble.compare("You Get A Raise") == 0) {
int raise_value = rand()%10;
cout << "You get a " << raise[raise_value] << " $ Raise" << endl;
salary += raise[raise_value];
cout << "New salary is $" << salary << endl;
}

How to get my program to read thru errors

I have an assignment for school in which the goal is to read data from a text file, and output calculations made with the info. I've gotten the inputing and outputting mostly down, but our prof wants us to include error checking aswell. I've done error checking for strings, and now im working on ints/doubles. The only issue is when i try to use the sample error input file he provided, my while loop dosen't fire at all.
bool isWord(string s)
{
for (int i = 0; i < s.length(); ++i)
{
if (::isdigit(s[i])){
return false;
}
}
return true;
}
int main()
{
ifstream inData;
ofstream outData;
inData.open("inData.txt");
outData.open("outData.txt");
//check for Error
if (inData.fail()){
cout << "Error opening file!" << endl;
exit(1);
}
if (outData.fail()){
cout << "Error opening file!" << endl;
exit(1);
}
double rWidth;
double rLength;
double cRad;
double number = 0;
string fName;
string lName;
string word;
int age;
int i = 0;
int savings;
int count = 0;
int people = 0;
int tAge = 0;
int tSavings = 0;
string names[256];
double tLength = 0;
double tWidth = 0;
double tArea = 0;
double perimeter = 0;
double tRad = 0;
double tCarea = 0;
double tCirc = 0;
while(inData >> rWidth >> rLength >> cRad >> fName >> lName >> age >> savings){
cout << rWidth << " " << rLength << " " << cRad << " " << fName << " " << lName << " " << age << " " << savings << "\n";
stringstream fNameStream(fName);
stringstream lNameStream(lName);
while (fNameStream >> word)
{
if (isWord(fName))
{
names[count++] = word;
}
else
{
names[count++] = "John";
}
}
while (lNameStream >> word)
{
if (isWord(lName))
{
names[count++] = word;
}
else
{
names[count++] = "Doe";
}
}
istringstream widthStream(rWidth);
while (widthStream >> number)
{
if (widthStream >> number)
{
widthStream >> rWidth;
}
else
{
rWidth = 0.0;
}
}
tLength = tLength + rLength;
tWidth = tWidth + rWidth;
perimeter = perimeter + (2*(rWidth+rLength));
tArea = tArea + (rWidth*rLength);
tRad = tRad + cRad;
tCarea = tCarea + pow(cRad, 2) * M_PI;
tCirc = tCirc + (2*M_PI*cRad);
tAge = tAge + age;
tSavings = tSavings + savings;
}
cout << tLength << "\n";
cout << tWidth << "\n";
cout << perimeter << "\n";
cout << tArea << "\n";
cout << tCarea << "\n";
cout << tCirc << "\n";
cout << tAge << "\n";
cout << tSavings < "\n";
cout << count << "\n";
while (i < count)
{
cout << names[i] << " ";
i++;
}
outData << "Rectangle: \n";
outData << "The total length= " << tLength << ", width= " << tWidth << ", area= " << tArea << "\n";
outData << "Perimeter= " << perimeter << "\n\n";
outData << "Circle:\n";
outData << "The total radius= " << tRad << ", area= " << tCarea << ", circumference= " << tCirc << "\n\n";
outData << "People:\n" << "Total number of people= " << count << "\n" << "Total Age= " << tAge << "\nTotal Savings= " << tSavings;
inData.close();
outData.close();
system("pause");
return 0;
}
Hopfully thats formatted correctly.
The program runs fine and dandy when i use:
10.45 8.76
13.78
Jake Melon 45
7600
128 76.9
11
Mike Sander 56
800
15.9 43
6400
David James 32
87000.54
But when i use:
10.45 aaaa
13.78
Jake Melon 45
7600
128 76.9
;
Mike Sander 23
800
15.9 43
w
David James i
87000.54
My main while loop (where I read data) doesn't fire for some reason, and all of my values remain at 0. Your help will be greatly appreciated! And I'm sorry for such a long block of text.
Error recovery is difficult and there are no standard methods (think about how your compiler recovers from a syntax error).
You will need an outer loop for your while loop. You'll want to come up with a design that will help you resynchronize on the input format. Again, not an easy task.
A simple method is to count the text lines and display the text line where the failure existed and end the program. From that you can display more information, such as the field that was in error. Some programmers assume the worst that once an error is found the remaining data can't be trusted.
I recommend putting in place a simple error announcement and safely terminate (clean up, flush to disk, etc.). Work on getting the remainder of your program working correctly, then come up with better error handling strategies.

When writing to a file, only the last line saves to my output file

Im trying to write to a file but only the last line gets written to the file. I've tried opening and closing the file outside the loop but then nothing writes to the file
void getValues (double totalEnergy, double meanPowerConsumption, double maxPowerConsumption);
int main()
{
double totalEnergy, meanPowerConsumption, maxPowerConsumption;
getValues(totalEnergy, meanPowerConsumption, maxPowerConsumption);
return 0;
}
void getValues(double totalEnergy, double meanPowerConsumption, double maxPowerConsumption)
{
int x = 0;
int c = 0;
double p = 0;
int i = 0;
ifstream inFile;
inFile.open("data.txt");
if (inFile.fail())
{ cerr << "Error opening file." << endl;
exit(1);
}
// Declaring variables.
double power1, power2, time1, time2, totalPower, timeConstant, changeInPower, totalTime, time, coloumns;
double year, month, day, hour, minute, second, voltage, current, frequency;
double accumulatedPower=0;
while(!inFile.eof())
{
inFile >> year >> month >> day >> hour >> minute >> second >> voltage >> current >> frequency;
//Should have taken into account 'Years','Months' and 'Days' but its throws the calculations into exponents.
time2 = ((3600*hour) + (minute *60) + second);
if (x==0)
{
timeConstant = 0;
time1 = 0;
totalTime = 0;
}
else
{
timeConstant = time2 - time1;
totalTime = totalTime + timeConstant;
}
//cout << "time1: " << time1 << endl;
//cout << "time2: " << time2 << endl;
//cout << "Time Constant: " << timeConstant<< endl;
//cout << "Total Time" << totalTime << endl;
power2 = voltage*current;
if (x==0)
{
power1 = 0;
changeInPower = 0;
totalPower = 0;
totalEnergy = 0;
meanPowerConsumption = 0;
}
else
{
changeInPower = (power1 + power2)/2;
totalPower = totalPower + changeInPower;
}
// cout << "Counter" << c << endl;
// Assumed that mean powerconsumption is the average of all powers entered.
meanPowerConsumption = totalPower / c;
// Testing Variables.
//cout << "power1: " << power1 << endl;
//cout << "power2: " << power2 << endl;
//cout << "Change in Power: " << changeInPower << endl;
//cout << "total Power: " << totalPower << endl;
//Numerical Integration:
totalEnergy = totalEnergy + (timeConstant*changeInPower);
//Counter Loop:
if (power2 > maxPowerConsumption)
{
maxPowerConsumption = power2;
}
accumulatedPower = accumulatedPower + power1;
time = time2 - time1;
p = p + time;
ofstream outFile;
outFile.open("byhour.txt");
for (coloumns=0; p>=3599; coloumns++)
{
i++;
outFile << i << " " << accumulatedPower/3600000 << endl;
accumulatedPower=0;
p=0;
}
outFile.close();
cout << "coloumns: " << i << endl;
cout << "P value " << p << endl;
cout << "accumulated power" << accumulatedPower << endl;
cout << "The total Energy is: " << totalEnergy/3600000 << "KwH" << endl;
cout << "The mean power consumption is: " << meanPowerConsumption << endl;
cout << "The Max Power Consumption is:" << maxPowerConsumption << endl;
cout << endl ;
c++;
x++;
time1 = time2;
power1 = power2;
}
ofstream outStats;
outStats.open("stats.txt");
outStats << totalEnergy/3600000 << endl;
outStats << meanPowerConsumption << endl;
outStats << maxPowerConsumption << endl;
outStats.close();
}
That's the full code. I tried taking it out and putting it back in (open and close file). Nothing has worked so far
You are opening and closing the file in a loop; based on the default mode it's opening to the first position in the file, so each write you are opening the file, writing to the start of the file (likely overwriting what was there before), and closing it.
You should open the file once, write out in a loop, and close outside the loop.
Your for loop is actually running (at most) once.
for (coloumns=0; p>=3599; coloumns++)
{
...
p=0;
}
Assuming p is at least 3599 at the start of the loop, the loop will run only a single time, because p gets set to 0 at the end of the loop (meaning the test will be false the next time around and the loop stops).
If p is less than 3599 at the start, of course, it won't run at all.

Password count help

void getPassword()
{
while (true)
{
string password;
cout << "Enter the password: ";
getline(cin, password);
if (password == "123456") break;
cout << "INVALID. ";
} // while
} // getPassword
int main()
{
getPassword();
double P;
double r;
double N = 360;
double rate;
cout << "What's the mortgage amount? ";
cin >> P;
cin.ignore(1000, 10);
cout << "What's the annual interest rate? ";
cin >> r;
cin.ignore(1000, 10);
rate = r / 100 / 12;
// (p * (1 + r)n * r) / ((1 + r)n - 1)
double M = P * ((pow))(1 + rate, N) * rate / (((pow))(1 + rate, N) -1);
cout.setf(ios::fixed|ios::showpoint);
cout << setprecision(2);
cout << "Principal = $" << P << endl;
cout.unsetf(ios::fixed|ios::showpoint);
cout << setprecision(6); // resets precision to its default
cout << "Interest Rate = " << r << "%" << endl;
cout << "Amortization Period = " << N / 12 << " years" << endl;
cout << "The monthly payment = $" << M << endl;
ofstream fout;
fout.open("mortgages.txt", ios::app);
if (!fout.good()) throw "I/O error";
fout.setf(ios::fixed|ios::showpoint);
fout << setprecision(2);
fout << "Principal = $" << P << endl;
fout.unsetf(ios::fixed|ios::showpoint);
fout << setprecision(6); // resets precision to its default
fout << "Interest Rate = " << r << "%" << endl;
fout << "Amortization Period = " << N / 12 << " years" << endl;
fout << "The monthly payment = $" << M << endl;
fout.close();
return 0;
}
What's up guys? I have a homework assignment for comsc and I have hit a roadblock in my last program. What I am attempting to do is limit the user of this program to 3 invalid password attempts. Do I need to change this to a value-returning subprogram or can I accomplish this without doing so? Any help would be much appreciated!!
Easiest way would be to change getPassword so that it returns a bool that signifies whether the user put in the right password. Then, rather than while (true), say for (int i = 0; i < 3; ++i)...and rather than break, return true. After the loop, return false since they went 3 rounds without putting in the right password.
In the rest of the program, rather than just calling getPassword, check its return value. If it's false, print an error message and exit.
Something like:
bool checkPassword() { // renaming this, since it doesn't just *get* a password
for (int i = 0; i < 3; ++i) {
string password;
std::cout << "Enter password: " << std::flush;
std::getline(std::cin, password);
if (password == "123456") return true;
std::cout << "INVALID.\n";
}
std::cout << "Maximum attempts exceeded.\n";
return false;
}
int main() {
if (!checkPassword()) {
return 1;
}
... rest of main() here ...
}