从文件c ++读取/写入数组

时间:2014-01-18 08:11:32

标签: c++ arrays file

我是c ++的初学者,我试图弄清楚文件的输入/输出是如何工作的。这个程序应该将一个整数数组写入一个文件,然后从文件中读取它,对它进行排序,得到平方整数的数量,然后将结果写回文件中。但是,当我尝试编译它时,它会告诉它我认为“”<<“操作数对于班级来说是非法的”。有人可以告诉我是什么事吗? 我试图避免使用.get和.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;
}

1 个答案:

答案 0 :(得分:0)

您正在多次重新定义myfile。更改main(),以便每个声明都是唯一的。这将在GCC

上编译
int main() {
   int i, arr[10], *p = &arr[0], sq;
   char name[50];
   cout << "Give the file's name:";
   cin >> name;
   ofstream myfile1(name, ios::out);
   cout << "Give the elements:";
   for (i = 0; i < 10; i++)
      myfile1 << *(p + i);
   myfile1.close();

   ifstream myfile2(name, ios::in);
   for (i = 0; i < 10; i++)
      myfile2 >> *(p + i);
   sq = squares(arr);
   sorting(arr);
   myfile2.close();
   ofstream myfile3(name, ios::app);
   for (i = 0; i < 10; i++) {
      myfile3 << "The sorted array is:";
      myfile3 << *(p + i);
   }
   myfile3 << "The number of square numbers is: " << sq;
   myfile3.close();
   return 0;
}