I have a program that prompts the user to enter a file name which in my case is grades1.txt which has the numbers 90 86 95 76 92 83 100 87 91 -1. Then I want it to read the file get the average of those numbers then ask the user to name a different file so those same 10 numbers can be stored in that different file. My error is that I get a segmentation fault.
This is my code so far
#include <iostream>
#include <fstream>
usingnamespace std;
int averageGrades(int grade[], int a);
//ask the user for the file that they want to use which in my case is grades1.txt
void readFile()
{
ifstream instream;
int grade[9];
char nameofFile[256];
cout << "Source file: ";
cin >> nameofFile[256];
instream.open("nameofFile[256]");
for(int a = 0; a < 10; a++)
instream >> grade[a];
instream.close();
}
//ask the user to give a name of a file to create a new txt file with the same numbers as grades1.txt
void writeFile(int grade[])
{
char fileName[256];
ofstream outstream;
cout << "Destination file: ";
cin >> fileName[256];
outstream.open("fileName[256]");
for(int b = 0; b < 10; b++)
outstream << grade[b];
outstream.close();
}
//calculates the average
int averageGrades(int grade[], int a)
{
int sum = 0;
int j, count = 0;
for(j = 0;j < a; j++)
{
sum += grade[j];
if(grade[j] == -1)
;
else
count++;
}
if(sum == -10)
return sum;
elsereturn sum / count;
}
int main()
{
int grade[9], a;
int quotion;
readFile();
quotion = averageGrades(grade, a);
if(quotion == -10)
cout << "Average Grade: ---%";
else
cout << "Average Grade: " << quotion << "%";
writeFile(grade);
cout << "File written successfully";
return 0;
}
On line 55, you pass "a" as the size of the array, though it hasn't been initialized to 9 like it should be. You might also want to note that readFile() does nothing, as it simply creates and edits some local variables that are destroyed when the function closes.
I'm still a little confused so what do I do to fix readFile() I want it to ask the user for a specific file and then put those numbers into the array. and I did initialize it readFile() and in main.