【问题标题】:Reading/writing array from file c++从文件c ++读取/写入数组
【发布时间】:2014-01-18 08:11:32
【问题描述】:

我是 C++ 的初学者,我试图弄清楚文件中的输入/输出是如何工作的。该程序应该将整数数组写入文件,然后从文件中读取,对其进行排序,获取平方整数的数量,然后将结果写回文件中。但是,当我尝试编译它时,它告诉我认为““

#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;
}

【问题讨论】:

  • 为您添加了 C++ 标签。对缩进做一些事情。
  • 嗯,首先,你重新定义myfile 几次。相反,每次使用 ifstream myfile(name, ios::in); 时都会附加一个数字。所以ifstream myfile1(name, ios::in);ifstream myfile2(name, ios::in);ifstream myfile3(name, ios::in);

标签: c++ arrays file


【解决方案1】:

您多次重新定义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;
}

【讨论】:

  • 但现在它不允许我从控制台给出数字
  • 我认为你需要更多&lt;&lt; cin。您只需向用户询问一个变量,即文件名。
  • 问题解决了。剩下的唯一问题是:例如,如果我使用fstream stream_name(filename, ios::in | ios::out),我是否能够仅使用那个流读取和写入文件?
  • @Georgiana std::basic_fstream&lt;...&gt; 是一个双向文件流,所以是的,你有读写功能。但请注意,::out::in 打开模式的显式规范是不必要的,因为它是默认打开方式。如果不需要其他打开模式,您可以简单地使用std::fstream f(filename) 打开它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-15
  • 2014-08-19
  • 2017-09-23
  • 1970-01-01
  • 2013-03-17
  • 1970-01-01
相关资源
最近更新 更多