【发布时间】: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);。