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

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.

Related

How to move back and forth in array list C++?

So I want to search my array for my data and move back and forth, so this is what i came up with, however this isn't working, can there be a better way to do this ? I tried to google some tips however I wasn't finding a suitable way to do this...
Can binary search be used to do this same thing ?
struct student
{
int stid = NULL;
char stname[15] = "NULL";
int grades = NULL;
string date = NULL;
};
int main()
{
int choose = 0;
int stid = 0;
int array = 1;
struct student s[1] = { 001, "Sara", "123456", "Canada", "02/01/2019" };
while (choose != 4)
{
cout << "1. Add\n";
cout << "2. View\n";
cout << "3. Search\n";
cout << "4. Quit\n";
cin >> choose;
if (choose == 3)
{
cout << "How would you like to find the Student Details?" << endl;
cout << "1 - By student id " << endl;
int choice = 0;
cin >> choice;
if (choice == 1)
{
cout << "Student ID: ";
cin >> stid;
for (int i = 0; i < array; i++)
{
if (s[i].stid == stid)
{
cout << "ID: " << s[i].stid << "\n";
cout << "Name: " << s[i].stname << "\n";
cout << "Grades: " << s[i].grades << "\n";
cout << "Date joined school: " << s[i].date<< "\n";
while (true)
{
cout << "Which record do you wish to see?" << endl;
cout << " 1 : Forth " << endl;
cout << " 2 : Back " << endl;
int choice = 0;
cin >> choice;
if (choice == 1)
{
stid = stid + 1;
for (int i = 0; i == stid; i++)
{
if (s[i].stid == stid)
{
cout << "ID: " << s[i].stid << "\n";
cout << "Name: " << s[i].stname << "\n";
cout << "Grades: " << s[i].grades << "\n";
cout << "Date joined school: " << s[i].date<< "\n";
}
}
}
else if (choice == 2)
{
stid = stid - 1;
for (int i = 0; i == stid; i++)
{
if (s[i].stid == stid)
{
cout << "ID: " << s[i].stid << "\n";
cout << "Name: " << s[i].stname << "\n";
cout << "Grades: " << s[i].grades << "\n";
cout << "Date joined school: " << s[i].date<< "\n";
}
}
}
Thank you for helping.

Array of Structures - Functions not pulling through data

I am studying BscCS so I am familiar with programming concepts, however I always seem to get stuck on structs and arrays of structs.
I am required to convert parallel arrays into an array of structs. I have done this, but for some reason the information is not getting sent to the functions properly and the program keeps crashing.
Could you help identify where I am going wrong of if there is something I am missing? I don't need exact code for answers, just some guidance. Here is the code:
#define SIZE 3
struct Employee {
string firstName[SIZE];
string lastName[SIZE];
int id[SIZE];
int hoursWorked[SIZE];
int payRate[SIZE];
int stat[SIZE];
};
//Functions
int menu();
void printReport(Employee & employees);
void search(Employee & employees);
void calculatePay(Employee & employees);
void orderByLastName(Employee & employees);
void orderByid(Employee & employees);
void printActive(Employee & employees);
void printInactive(Employee & employees);
//Display Main Menu
int menu()
{
int choice;
cout << "1. Print out Employee Report. " << endl;
cout << "2. Search Employee Records. " << endl;
cout << "3. Display the Report in Sorted order on Last Name or ID. << endl;
cout << "4. Calculate Pay. " << endl;
cout << "5. Display Active Employees." << endl;
cout << "6. Display Inactive Employees." << endl;
cout << "7. Quit" << endl;
cout << "Enter your choice. ";
cin >> choice;
return choice;
}
//Display the employee data in a formatted order
void printReport(Employee & employees)
{
cout << setw(10) << "First Name" <<
setw(10) << "Last Name" <<
setw(10) << "ID" <<
setw(10) << "Hours" <<
setw(10) << "Rate" <<
endl;
ios::fixed;
for (int index = 0; index < SIZE; index++)
cout << setw(10) << employees.firstName[index] <<
setw(10) << employees.lastName[index] <<
setw(10) << employees.id[index] <<
setw(10) << employees.hoursWorked[index] <<
setw(10) << employees.payRate[index] << endl;
}
//Search for employee ID
//Show "Not Found" if unable to locate
void search(Employee & employees)
{
bool found = false;
int idNumber;
int pos = -1;
cout << "Enter id number ";
cin >> idNumber;
for (int index = 0; index < SIZE && !found; index++)
{
if (employees.id[index] == idNumber)
{
found = true;
pos = index;
}
}
if (!found)
cout << "Not Found. " << endl;
else
cout << setw(10) << employees.firstName[pos] <<
setw(10) << employees.lastName[pos] <<
setw(10) << employees.id[pos] <<
setw(10) << employees.hoursWorked[pos] <<
setw(10) << employees.payRate[pos] << endl;
}
//Calculate total weekly pay
void calculatePay(Employee & employees)
{
cout << setw(10) << "First Name" <<
setw(10) << "Last Name" <<
setw(10) << "ID" <<
setw(10) << "Hours" <<
setw(10) << "Rate" <<
setw(10) << "Total Pay" <<
endl;
ios::fixed;
for (int index = 0; index < SIZE; index++)
cout << setw(10) << employees.firstName[index] <<
setw(10) << employees.lastName[index] <<
setw(10) << employees.id[index] <<
setw(10) << employees.hoursWorked[index] <<
setw(10) << employees.payRate[index] <<
setw(10) << employees.hoursWorked[index] * employees.payRate[index] << endl;
}
//Sort employee data by last name
void orderByLastName(Employee & employees)
{
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE - 1; j++)
{
if (employees.lastName[j] > employees.lastName[j + 1])
{
string temp = employees.lastName[j];
employees.lastName[j] = employees.lastName[j + 1];
employees.lastName[j + 1] = temp;
temp = employees.firstName[j];
employees.firstName[j] = employees.firstName[j + 1];
employees.firstName[j + 1] = temp;
int tempid = employees.id[j];
employees.id[j] = employees.id[j + 1];
employees.id[j + 1] = tempid;
int temphours = employees.hoursWorked[j];
employees.hoursWorked[j] = employees.hoursWorked[j + 1];
employees.hoursWorked[j + 1] = temphours;
int temppayrate = employees.payRate[j];
employees.payRate[j] = employees.payRate[j + 1];
employees.payRate[j + 1] = temppayrate;
}
}
}
}
//Sort employee data by ID
void orderByid(Employee & employees)
{
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE - 1; j++)
{
if (employees.id[j] > employees.id[j + 1])
{
string temp = employees.lastName[j];
employees.lastName[j] = employees.lastName[j + 1];
employees.lastName[j + 1] = temp;
temp = employees.firstName[j];
employees.firstName[j] = employees.firstName[j + 1];
employees.firstName[j + 1] = temp;
int tempid = employees.id[j];
employees.id[j] = employees.id[j + 1];
employees.id[j + 1] = tempid;
int temphours = employees.hoursWorked[j];
employees.hoursWorked[j] = employees.hoursWorked[j + 1];
employees.hoursWorked[j + 1] = temphours;
int temppayrate = employees.payRate[j];
employees.payRate[j] = employees.payRate[j + 1];
employees.payRate[j + 1] = temppayrate;
}
}
}
}
void printActive(Employee & employees)
{
bool found = false;
int pos = -1;
for (int index = 0; index < SIZE && !found; index++)
{
if (employees.stat[index] == 1)
{
found = true;
pos = index;
}
if (!found) {
cout << "No active employees." << endl;
}
else {
cout << setw(10) << employees.firstName[pos] <<
setw(10) << employees.lastName[pos] <<
setw(10) << employees.id[pos] <<
setw(10) << employees.hoursWorked[pos] <<
setw(10) << employees.payRate[pos] << endl;
}
}
}
void printInactive(Employee & employees)
{
bool found = false;
int pos = -1;
for (int index = 0; index < SIZE && !found; index++)
{
if (employees.stat[index] == 0)
{
found = true;
pos = index;
}
if (!found) {
cout << "No inactive employees." << endl;
}
else {
cout << setw(10) << employees.firstName[pos] <<
setw(10) << employees.lastName[pos] <<
setw(10) << employees.id[pos] <<
setw(10) << employees.hoursWorked[pos] <<
setw(10) << employees.payRate[pos] << endl;
}
}
}
int main()
{
struct Employee employees[SIZE];
//Read first and last name from user
for (int index = 0; index < SIZE; index++)
{
cout << "Enter first name : ";
cin >> employees[index].firstName[index];
cout << "Enter last name : ";
cin >> employees[index].lastName[index];
//Read ID, hours, and pay rate from user
while (employees[index].id[index] < 0)
{
cout << "Enter id : ";
cin >> employees[index].id[index];
if (employees[index].id[index] < 0)
{
cout << "Invalid Id number. " << endl;
cout << "Enter id : ";
cin >> employees[index].id[index];
}
}
while (employees[index].hoursWorked[index] < 0)
{
cout << "Enter hours worked : ";
cin >> employees[index].hoursWorked[index];
if (employees[index].hoursWorked[index] < 0)
{
cout << "Invalid hours. " << endl;
cout << "Enter hours worked : ";
cin >> employees[index].hoursWorked[index];
}
}
while (employees[index].payRate[index] < 0)
{
cout << "Enter Pay Rate : ";
cin >> employees[index].payRate[index];
if (employees[index].payRate[index] < 0)
{
cout << "Invalid pay rate. " << endl;
cout << "Enter Pay Rate : ";
cin >> employees[index].payRate[index];
}
}
while (employees[index].stat[index] < 0)
{
cout << "Enter your status. (0 - Inactive, 1 - Active) : ";
cin >> employees[index].stat[index];
if (employees[index].stat[index] < 0)
{
cout << "Enter your status : ";
cin >> employees[index].stat[index];
}
cout << endl;
}
}
//Loop to display menu options until user quits program
while (true)
{
//Call menu with options
int ch = menu();
//Different options to choose
switch (ch)
{
case 1:
printReport(employees[SIZE]);
break;
case 2:
search(employees[SIZE]);
break;
case 3:
int sortType;
cout << "1.Sort by Last Name." << endl;
cout << "2.Sort by ID." << endl;
cout << "Enter your choice. ";
cin >> sortType;
if (sortType == 1)
orderByLastName(employees[SIZE]);
else if (sortType ==2)
orderByid(employees[SIZE]);
break;
case 4:
calculatePay(employees[SIZE]);
break;
case 5: printActive(employees[SIZE]);
case 6: printInactive(employees[SIZE]);
break;
case 7:
exit(0);
}
}
system("pause");
return 0;
}
Thank you in advance!
I ran your program, and I received more than 20 errors before the compiler involuntarily stopped trying to compile any longer. All of them are connected to the lines of code using cout, cin, string, and setw. You need to use these keywords with the std namespace to fix this, and you need to include the iostream header file (#include <iostream>). Either you can write std:: in front of all of these keywords (i.e. std::cout) or you can declare the namespace in the preprocessor (using namespace std;). Also, for std::setw, you need to include the iomanip header file (#include <iomanip>). After that, you're missing a quotation in the menu function and a bracket at the end of the main function. (There's also a couple of problems with initializing the size of the struct members in the declaration, but I'll leave that up to you.) Hope this helped!

Confusing Syntax Error

I am making a program that takes info from a file then puts it into a struct then makes an array of structs. I have the program done, but when I compile I get 2 errors. "Expected Declaration" and "Syntax Error: Constant" both pointing to the first line of the read in file. I am at a loss and I am not sure how to get it running. My code I am using looks like this:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <stdlib.h>
using namespace std;
struct book
{
int ISBN;
string Author;
string Title;
int Quantity;
double price;
};
void choice1(book books[], int& size, int MAX_SIZE)
{
ifstream inFile;
inFile.open("Inventory.txt");
string str;
while (inFile && size < MAX_SIZE)
{
getline(inFile, str);
books[size].ISBN = atoi(str.c_str());
getline(inFile, books[size].Author);
getline(inFile, books[size].Title);
getline(inFile, str);
books[size].Quantity = atoi(str.c_str());
getline(inFile, str);
books[size].price = atoi(str.c_str());
getline(inFile, str);
size++;
}
cout << "You have successfully read the file." << endl;
inFile.close();
}
void choice2(book books[], int size)
{
for (int i = 0; i < size; i++)
{
cout << endl;
cout << "Book Number: " << (i + 1) << endl;
cout << "ISBN: " << books[i].ISBN << endl;
cout << "Author: " << books[i].Author << endl;
cout << "Title: " << books[i].Title << endl;
cout << "Quantity: " << books[i].Quantity << endl;
cout << "Price: $" << books[i].price << endl;
}
if (size != 0)
cout << "You have successfully printed the array." << endl;
else
cout << "Array is empty. Read the file first." << endl;
}
void choice3(book books[], int size)
{
if (size == 0)
cout << "Array is empty. Read the data first." << endl;
else
{
int isbn;
int option;
int qty;
cout << "\nEnter the ISBN of the book: ";
cin >> isbn;
cout << "1. Increment" << endl;
cout << "2. Decrement" << endl;
cout << "3. Add New" << endl;
cout << "Enter your option: ";
cin >> option;
cout << "Enter the quantity: ";
cin >> qty;
for (int i = 0; i < size; i++)
{
if (books[i].ISBN == isbn)
{
if (option == 1)
books[i].Quantity += qty;
else if (option == 2)
{
books[i].Quantity -= qty;
if (books[i].Quantity)
books[i].Quantity = 0;
}
else if (option == 3)
books[i].Quantity = qty;
break;
}
}
cout << "You have successfully updated the array." << endl;
}
}
void choice4(book books[], int& size, int MAX_SIZE)
{
if (size < MAX_SIZE)
{
string str;
cout << "\nEnter the book ISBN: ";
cin >> books[size].ISBN;
cout << "Enter the author name: ";
cin >> books[size].Author;
cout << "Enter the book tile: ";
cin >> books[size].Title;
cin.get();
cout << "Enter the books quantity: ";
cin >> books[size].Quantity;
cout << "Enter the book price: $";
cin >> books[size].price;
size++;
cout << "You have successfully inserted an entry." << endl;
}
}
void choice5(book books[], int size)
{
for (int i = 1; i < size; i++)
{
book current = books[i];
int j = i;
while (j > 0 && (books[j - 1].Title).compare(current.Title) > 0)
{
books[j] = books[j - 1];
j--;
}
books[j] = current;
}
if (size != 0)
cout << "You have successfully sorted the array." << endl;
else
cout << "Array is empty. Read the data first." << endl;
}
void choice6(book books[], int& size)
{
if (size == 0)
cout << "Array is empty. Read the data first." << endl;
else
{
int isbn;
cout << "\nEnter the ISBN of the book: ";
cin >> isbn;
for (int i = 0; i < size; i++)
{
if (books[i].ISBN == isbn)
{
int j = i;
while (j < size - 1)
{
books[j] = books[j + 1];
j++;
}
size--;
break;
}
}
cout << "You have successfully deleted an entry." << endl;
}
}
void choice7(book books[], int size)
{
ofstream outFile;
outFile.open("finalData.dat");
for (int i = 0; i < size; i++)
{
outFile << "Book Number: " << (i + 1) << endl;
outFile << "ISBN: " << books[i].ISBN << endl;
outFile << "Author: " << books[i].Author << endl;
outFile << "Title: " << books[i].Title << endl;
outFile << "Quantity: " << books[i].Quantity << endl;
outFile << "Price: $" << books[i].price << endl << endl;
}
if (size != 0)
cout << "You have successfully printed the array." << endl;
else
cout << "Array is empty. Read the file first." << endl;
outFile.close();
}
// File: Boookstore.cpp
#include<iostream>
#include"Inventory.txt"
using namespace std;
int main()
{
const int MAX_SIZE = 100;
int size = 0;
int choice;
book books[MAX_SIZE];
do
{
cout << "1: Read inventory forn file" << endl;
cout << "2: Display Inventory" << endl;
cout << "3: Update an entry" << endl;
cout << "4: Add an entry" << endl;
cout << "5: Sort inventory" << endl;
cout << "6: Delete an entry" << endl;
cout << "7: Write inventory to file and exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
switch (choice)
{
case 1:
choice1(books, size, MAX_SIZE);
break;
case 2:
choice2(books, size);
break;
case 3:
choice3(books, size);
break;
case 4:
choice4(books, size, MAX_SIZE);
break;
case 5:
choice5(books, size);
break;
case 6:
choice6(books, size);
break;
case 7:
choice7(books, size);
cout << "Thank you." << endl;
break;
default:
cout << "Invalid choice!" << endl;
}
cout << endl;
} while (choice != 7);
system("pause");
return 0;
}
I have the read in file in the same folder as my source file, but I am not sure what is causing the issue. My read in file is exactly this:
20451
My First Book
Mark Lusk
Pearson Publishing
40
45.34
9780316
Brown Family
Mason Victor
Little Brown
36
105.99
1349877
Story of My Life
Norah M Jones
CreateSpace Independent Publishing Platform
20
18
It is supposed to take the first line of the file and set it as an int to the ISNB section of my struct, but it just keeps telling me it is a constant. Any help is appreciated!
You can't #include a data file. It will treat it like part of your code - and it's obviously not valid c++.
#include "Inventory.txt"
You have to open the file and read it with things like ifstream.

(C++) Error expected unqualified-id before numeric constant-- When Reading in From a File

I am really stumped on this one. I am making a program that takes info in from a file and then puts it into structs and then the structs into arrays. My problem appears to come after I compile. I do not show any errors in the code itself, but the error comes up as the first line of the read in file.
My Code is as follows:
// File: Inventory.txt
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <stdlib.h>
using namespace std;
struct book
{
int ISBN;
string Author;
string Title;
int Quantity;
double price;
};
void choice1(book books[], int& size, int MAX_SIZE)
{
ifstream inFile;
inFile.open("inventory.txt");
string str;
while(inFile && size < MAX_SIZE)
{
getline(inFile, str);
books[size].ISBN = atoi(str.c_str());
getline(inFile, books[size].Author);
getline(inFile, books[size].Title);
getline(inFile, str);
books[size].Quantity = atoi(str.c_str());
getline(inFile, str);
books[size].price = atoi(str.c_str());
getline(inFile, str);
size++;
}
cout << "You have successfully read the file." << endl;
inFile.close();
}
void choice2(book books[], int size)
{
for(int i = 0; i < size; i++)
{
cout << endl;
cout << "Book Number: " << (i + 1) << endl;
cout << "ISBN: " << books[i].ISBN << endl;
cout << "Author: " << books[i].Author << endl;
cout << "Title: " << books[i].Title << endl;
cout << "Quantity: " << books[i].Quantity << endl;
cout << "Price: $" << books[i].price << endl;
}
if(size != 0)
cout << "You have successfully printed the array." << endl;
else
cout << "Array is empty. Read the file first." << endl;
}
void choice3(book books[], int size)
{
if(size == 0)
cout << "Array is empty. Read the data first." << endl;
else
{
int isbn;
int option;
int qty;
cout << "\nEnter the ISBN of the book: ";
cin >> isbn;
cout << "1. Increment" << endl;
cout << "2. Decrement" << endl;
cout << "3. Add New" << endl;
cout << "Enter your option: ";
cin >> option;
cout << "Enter the quantity: ";
cin >> qty;
for(int i = 0; i < size; i++)
{
if(books[i].ISBN == isbn)
{
if(option == 1)
books[i].Quantity += qty;
else if(option == 2)
{
books[i].Quantity -= qty;
if(books[i].Quantity)
books[i].Quantity = 0;
}
else if(option == 3)
books[i].Quantity = qty;
break;
}
}
cout << "You have successfully updated the array." << endl;
}
}
void choice4(book books[], int& size, int MAX_SIZE)
{
if(size < MAX_SIZE)
{
string str;
cout << "\nEnter the book ISBN: ";
cin >> books[size].ISBN;
cout << "Enter the author name: ";
cin >> books[size].Author;
cout << "Enter the book tile: ";
cin >> books[size].Title;
cin.get();
cout << "Enter the books quantity: ";
cin >> books[size].Quantity;
cout << "Enter the book price: $";
cin >> books[size].price;
size++;
cout << "You have successfully inserted an entry." << endl;
}
}
void choice5(book books[], int size)
{
for(int i = 1; i < size; i++)
{
book current = books[i];
int j = i;
while(j > 0 && (books[j - 1].Title).compare(current.Title) > 0)
{
books[j] = books[j - 1];
j--;
}
books[j] = current;
}
if(size != 0)
cout << "You have successfully sorted the array." << endl;
else
cout << "Array is empty. Read the data first." << endl;
}
void choice6(book books[], int& size)
{
if(size == 0)
cout << "Array is empty. Read the data first." << endl;
else
{
int isbn;
cout << "\nEnter the ISBN of the book: ";
cin >> isbn;
for(int i = 0; i < size; i++)
{
if(books[i].ISBN == isbn)
{
int j = i;
while(j < size - 1)
{
books[j] = books[j + 1];
j++;
}
size--;
break;
}
}
cout << "You have successfully deleted an entry." << endl;
}
}
void choice7(book books[], int size)
{
ofstream outFile;
outFile.open("finalData.dat");
for(int i = 0; i < size; i++)
{
outFile << "Book Number: " << (i + 1) << endl;
outFile << "ISBN: " << books[i].ISBN << endl;
outFile << "Author: " << books[i].Author << endl;
outFile << "Title: " << books[i].Title << endl;
outFile << "Quantity: " << books[i].Quantity << endl;
outFile << "Price: $" << books[i].price << endl << endl;
}
if(size != 0)
cout << "You have successfully printed the array." << endl;
else
cout << "Array is empty. Read the file first." << endl;
outFile.close();
}
// File: Boookstore.cpp
#include<iostream>
#include"inventory.txt"
using namespace std;
int main()
{
const int MAX_SIZE = 100;
int size = 0;
int choice;
book books[MAX_SIZE];
do
{
cout << "1: Read inventory forn file" << endl;
cout << "2: Display Inventory" << endl;
cout << "3: Update an entry" << endl;
cout << "4: Add an entry" << endl;
cout << "5: Sort inventory" << endl;
cout << "6: Delete an entry" << endl;
cout << "7: Write inventory to file and exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
switch(choice)
{
case 1:
choice1(books, size, MAX_SIZE);
break;
case 2:
choice2(books, size);
break;
case 3:
choice3(books, size);
break;
case 4:
choice4(books, size, MAX_SIZE);
break;
case 5:
choice5(books, size);
break;
case 6:
choice6(books, size);
break;
case 7:
choice7(books, size);
cout << "Thank you." << endl;
break;
default:
cout << "Invalid choice!" << endl;
}
cout << endl;
}while(choice != 7);
system("pause");
return 0;
}
My Read in file (inventory.txt) is:
20451 <<The line that give the expected unqualified-id before numeric constant error
My First Book
Mark Lusk
Pearson Publishing
40
45.34
9780316
Brown Family
Mason Victor
Little Brown
36
105.99
1349877
Story of My Life
Norah M Jones
CreateSpace Independent Publishing Platform
20
18
I have been looking at my code for days and cannot find why I am getting this error! I do apologize if the answer is staring me in the face, but I could not find anything about getting this error from the file not the code. Any advise would be much appreciated!
This #include"inventory.txt" should probably be something like #include "inventory.h" if that header file exists.
// File: Boookstore.cpp
#include<iostream>
#include"inventory.txt"

Access Violation Violation Location With Low Numbers

I'm working on an assignment for school. The code is supposed to read form a file and create an array, then sort the values of the array to output certain info. It works just fine as long as I have 3+ lines of info in the file. If not, I get the following error:
First-chance exception at 0x01305876 in Homework11.exe: 0xC0000005: Access violation reading location 0xcd71b288.
Unhandled exception at 0x01305876 in Homework11.exe: 0xC0000005: Access violation reading location 0xcd71b288.
I can't figure out why, any help would be appreciated. Here's the code:
#include <iostream> //calls the information needed
#include <iomanip>
#include <algorithm>
#include <fstream>
#include <string>
using namespace std; //sets all unmarked commands to std::
const int ARRSIZE = 1000;
struct Student
{
string firstName;
string lastName;
string id, temp;
double gpa;
};
int readArray(ifstream& ifile, Student arr[]);
void swapElements(Student arr[], int i, int j);
void sortArray(Student arr[], int numberInTheArray);
int main()
{ // Declares the needed variables
double sought, min, max;
int i, ival, returnvar, count = 0, mincount, maxcount;
string filename;
ifstream ifile;
Student arr[ARRSIZE];
cout << "Input File Name: ";//requesting the file name
cin >> filename;
ifile.open(filename.c_str());//opening the file
if (!ifile)//checking if it opened or not
{
cout << endl << "That file does not exist!" << endl;//informing the user it did
return 1;//not open and returning 1
}
cout << "Which number do you want to return? ";//requesting the desired number
cin >> ival;
i = ival - 1;
cout << endl;
returnvar = readArray(ifile, arr);
min = arr[0].gpa;
max = arr[0].gpa;
sought = arr[0].gpa;
while (count < returnvar)
{
if (arr[count].gpa < min)
{
min = arr[count].gpa;
mincount = count;
}
if (arr[count].gpa > max)
{
max = arr[count].gpa;
maxcount = count;
}
if (count == i)
{
sought = arr[count].gpa;
}
count++;
}
if (count == 0)
{
cout << "The file is empty!" << endl;
return 1;
}
cout << "Before Sort:" << endl;
cout << " Min GPA is " << min << " for " << arr[mincount].lastName << "." << endl;
cout << " Max GPA is " << max << " for " << arr[maxcount].lastName << "." << endl;
if (returnvar < ARRSIZE)
{
cout << " WARNING: Only " << returnvar << " numbers were read into the array!" << endl;
}
if (i >= returnvar)
{
cout << " There aren't that many numbers in the array!" << endl << endl;
}
else if (i > ARRSIZE)
{
cout << " " << i << " is bigger than " << ARRSIZE << "!" << endl << endl;
}
else if (i < returnvar)
{
cout << " Value " << ival << " is " << sought << " for " << arr[i].lastName << "." << endl << endl;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
sortArray(arr, returnvar);
count = 0;
while (count < returnvar)
{
if (arr[count].gpa < min)
{
min = arr[count].gpa;
mincount = count;
}
if (arr[count].gpa > max)
{
max = arr[count].gpa;
maxcount = count;
}
if (count == i)
{
sought = arr[count].gpa;
}
count++;
}
cout << "After Sort:" << endl;
cout << " Array[0] GPA is " << min << " for " << arr[0].lastName << "." << endl;
cout << " Array[" << (returnvar - 1) << "] GPA is " << max << " for " << arr[(returnvar - 1)].lastName << "." << endl;
if (returnvar < ARRSIZE)
{
cout << " WARNING: Only " << returnvar << " numbers were read into the array!" << endl;
}
if (i >= returnvar)
{
cout << " There aren't that many numbers in the array!" << endl << endl;
}
else if (i > ARRSIZE)
{
cout << " " << i << " is bigger than " << ARRSIZE << "!" << endl << endl;
}
else if (i < returnvar)
{
cout << " Value " << ival << " is " << sought << " for " << arr[i].lastName << "." << endl << endl;
}
return 0;
}
int readArray(ifstream& ifile, Student arr[])
{
int counter = 0;
while ((ifile) && (counter <= ARRSIZE))
{
ifile >> arr[counter].firstName;
ifile >> arr[counter].lastName;
ifile >> arr[counter].id;
ifile >> arr[counter].gpa;
counter++;
}
return (counter - 1);
}
void sortArray(Student arr[], int numberInTheArray)
{
for (int i = 0 ; i < numberInTheArray - 1; i++)
{
for (int j = 0 ; j < numberInTheArray - 1; j++)
{
if ( arr[j].gpa > arr[j + 1].gpa)
{
swapElements(arr, j, j+1);
}
}
}
}
void swapElements(Student arr[], int i, int j)
{
Student temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
Please ignore the insanity and comments. Like I said, for an entry level course.
Try replacing counter <= ARRSIZE with counter < ARRSIZE (a rule of thumb in C is: never use <= in operations related to container sizes).
EDIT: also in your main(), you must check that i < ARRSIZE (equivalently, return error if i >= ARRSIZE). At present you seem to accept the case i == ARRSIZE, which is also wrong. And finally, readArray should return counter (that is, one more than the last written index).