【发布时间】:2022-01-02 05:14:08
【问题描述】:
我正在尝试进行分配,在该文件中我生成一个具有随机整数值的文件,然后将这些值放入一个数组中,但是,我不太确定如何执行此操作,因为我只收到了错误与我如何尝试这样做,所以我想知道是否有不同的方法来完成这项任务。我还附上了我的代码和带有随机整数的外部文本文件,您可能会注意到还有一些其他功能,但这些功能仅用于分配中的其他要求并创建 txt 文件。
#include <fstream>
#include <cstdlib>
using namespace std;
//function 1 Create File with rand numbers
void createfile() {
srand(time(0));
int counter = 0;
int generatednum = 0;
ofstream randNums("randomnumbers.txt");
for (int counter = 0; counter < 50; counter++) {
int generatednum = rand() % 105 + 2;
randNums << generatednum << endl;
}
randNums.close();
}
//function 2 count number of apples picked under 25
void countundertwentyfive() {
int under25count;
int under25amount = 0;
ifstream infile;
infile.open("randomnumbers.txt");
if (infile.fail())
{
cerr << "File failed to open:inputfile.txt";
abort();
}
while (!infile.eof()) {
infile >> under25count;
if (under25count < 25) {
under25amount++;
}
}
cout << under25amount << " people picked under 25 apples." << endl;
infile.close();
}
//function 3 count number of apples picked btwn 80 and 100
void btwn80and100() {
int eightyand100apples;
int under80and100amount = 0;
ifstream infile;
infile.open("randomnumbers.txt");
if (infile.fail())
{
cerr << "File failed to open:inputfile.txt";
abort();
}
while (!infile.eof()) {
infile >> eightyand100apples;
if (eightyand100apples >= 80 && eightyand100apples <= 100) {
under80and100amount++;
}
}
cout << under80and100amount << " people picked between 80 and 100 apples." << endl;
infile.close();
}
//function 4 Find average number of apples picked
void averageapplepicked() {
int numbergetter;
int sum = 0;
ifstream infile;
infile.open("randomnumbers.txt");
if (infile.fail())
{
cerr << "File failed to open:inputfile.txt";
abort();
}
while (!infile.eof()) {
infile >> numbergetter;
sum += numbergetter;
}
sum /= 50;
cout << "Approximately " << sum << " apples were picked on average" << endl;
infile.close();
}
//Use of previous functions along with the array thing I dont understand how to do
int main() {
createfile();
countundertwentyfive();
btwn80and100();
averageapplepicked();
int arrayvalues;
int arraydisplay;
ifstream infile;
infile.open("randomnumbers.txt");
if (infile.fail())
{
cerr << "File failed to open:inputfile.txt";
abort();
}
while (!infile.eof()) {
int arraydisplay[50] = { infile >> arrayvalues };
}
cout << arraydisplay[50] << endl;
infile.close();
return 0;
} ```
The txt file generated by the code
3
74
89
20
35
79
12
12
82
98
25
5
59
99
54
46
53
38
98
42
103
55
73
96
98
75
48
42
70
82
50
62
26
90
17
103
24
56
93
46
10
49
33
76
40
44
6
101
43
43
Thank you so much for any help!
【问题讨论】:
-
请阅读the help pages,接受SO tour,阅读How to Ask,以及this question checklist。然后edit你的问题添加更多细节,比如你得到了什么“错误”。