Is there something wrong in this function? Does this not gather all the data from the text file?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
void CopyRecords(string Fname)
{
fstream f;
f.open(Fname, ios::in);
for (int i = 0; i < N; i++)
{
f.getline(p[i].Name, 15, '/');
f >> p[i].Age >> p[i].Gpa;
}
f.close();
}
Is there something wrong in this function? Does this display all of the information stored from the structure?
1 2 3 4 5 6 7 8 9 10 11 12 13 14
void Display()
{
for (int i = 0; i < N; i++)
{
cout << p[i].Name << " " << p[i].Age << "/" << p[i].Gpa;
}
cout << endl;
// Have all data under variable Name uppercase
}
#include <iostream>
#include <fstream>
usingnamespace std;
constint N = 5;
struct RECORD
{
char Name[15];
int Age;
float Gpa;
};
RECORD p[N];
float GpaAve;
int main ()
{
ifstream f;
in.open("fileName.txt");
for (int i = 0; i < 5; i++)
{
f.getline(p[i].Name, 15, '/');
f >> p[i].Age >> p[i].Gpa;
}
for (int i = 0; i < 5; i++)
{
cout << "name " << p[i].Name << " age " <<p[i].Age << " gpa " << p[i].Gpa << endl; // does it show the desired?
}
return 0;
}
#include <iostream>
#include <fstream>
#include <array>
usingnamespace std;
struct PERSON
{
int age;
float gpa;
char name[20];
};
PERSON *p;
void ArraySize(string Fname, int &x);
void CopyData(string Fname, int x);
void DisplayData(int x);
int main()
{
int size;
ArraySize("two.txt", size); //determine dnynamic array size
cout << "The size of the array is " << size << endl;
CopyData("two.txt", size); //copy data from file to array p
DisplayData(size); //Display the data
system("PAUSE");
return 0;
}
void ArraySize(string Fname, int &x)
{
int n;
fstream f;
f.open(Fname, ios::in);
f >> n;
x = n;
f.close();
}
void CopyData(string Fname, int x)
{
ifstream f;
f.open(Fname, ios::in);
for (int i = 0; i < x; i++)
{
f >> p[i].age;
f >> p[i].gpa;
f.getline(p[i].name, 20, '\n');
}
f.close();
}
void DisplayData(int x)
{
for (int i = 0; i < x; i++)
{
cout << p[i].age << " " << p[i].gpa << " " << p[i].name << endl;
}
}
Why doesn't this work?
A window pops up saying: "Unhandled exception at x61D735BA (msvcp120d.dll) in Project7(2).exe: 0xC0000005: Access violation writing location 0x00000000.
You get the array size but never actually create the array.
p = new PERSON[size];
Then just don't forget to delete what you new before the end of main.
delete[] p;
don't you see i used them between line 24 and 29.
i am not writing everything along the way as an assignment - rather showing whats needed. and, when main ends it automatically delets the pointer - its a small program.
Same reason why you make some things const. to keep it safe. If you have data you don't want to over-write create an input stream. Then if you try to do something silly the compiler will yell at you.