I am a beginner in c++ and i'm trying to figure how the in/output in a file works. This program is supposed to write an array of integers into a file,then read it from file, sort it,get the number of square integers and then write the results back into the file.However,when i try to compile it , it tells me that " "<<" operand is illegal for class". Could anyone please tell me what is the matter? I'm trying to avoid using .get and .put.
#include <iostream>
#include <fstream>
using namespace std;
void sorting(int *p);
int squares(int *p);
int main() {
int i, arr[10], *p = &arr[0], sq;
char name[50];
cout << "Give the file's name:";
cin >> name;
ofstream myfile(name, ios::out);
cout << "Give the elements:";
for (i = 0; i < 10; i++)
myfile << *(p + i);
myfile.close();
ifstream myfile(name, ios::in);
for (i = 0; i < 10; i++)
myfile >> *(p + i);
sq = squares(arr);
sorting(arr);
myfile.close();
ofstream myfile(name, ios::app);
for (i = 0; i < 10; i++) {
myfile << "The sorted array is:";
myfile << *(p + i);
}
myfile << "The number of square numbers is: " << sq;
myfile.close();
return 0;
}
void sorting(int *p) {
int temp;
for (int i = 0; i < 9; i++)
for (int j = i + 1; j < 10; j++)
if (*(p + i)>*(p + j)) {
temp = *(p + i);
*(p + i) = *(p + j);
*(p + j) = temp;
}
}
int squares(int *p) {
int count = 0;
for (int i = 0; i < 10; i++)
if ((*(p + i) % 2) == 0)
count++;
return count;
}
myfileseveral times. Instead, every time you useifstream myfile(name, ios::in);append a number. Soifstream myfile1(name, ios::in);,ifstream myfile2(name, ios::in);, andifstream myfile3(name, ios::in);.