因此,我试图从一个文件中读取名称,并根据我想要的名称数将其输出到另一个文件中,但是当程序运行时,就没有输出了。我正在读取一个文件“names.txt”。为什么我没有得到任何输出,以及如何改进我的代码?我对c++有点陌生,所以任何反馈都是非常感谢的。
```js
//Purpose: Generate a file of students
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h> // for rand()
#include <time.h>
void GenerateFile(std::fstream &, std::string *, const int,
std::string *, std::string *, std::string *);
void randomizeNames(std::string *, const int);
int main()
{
int numRecords = 0;
srand(time(NULL));
std::cout << "Please enter the number of student records you want in your file: ";
std::cin >> numRecords;
while(numRecords > 120 || numRecords < 1)
{
std::cout << "You cannot create more than 120 records!"
<< "\nThat exceeds the number of available trays\n";
std::cout << "Please enter the number of student records you want generated: ";
std::cin >> numRecords;
}
std::string Schools[] = {"Eastville", "Westburg", "Northton", Southport", "Jahunga", "Podunk"};
std::string Entrees[] = {"Chicken", "Fishsticks", "Lasagna"};
std::string Desserts[] = {"Cheesecake", "Pudding"};
char InFile[] = "names.txt";
char OutFile[] = "Students.txt";
std::fstream Input(InFile, std::ios::in);
std::fstream Output(OutFile, std::ios::out);
std::string names[120];
int i = 0;
std::string s;
while(!Input.eof())
getline(Input, names[i++]); // Discards newline char
randomizeNames(names, i);
GenerateFile(Output, names, numRecords, Schools, Entrees, Desserts);
Input.close();
Output.close();
std::cout << "The file " << OutFile << " was created for you.\n\n";
return 0;
}
void GenerateFile(fstream &Out, string* name, const int records,
string* School, string* Entree, string* Dessert )
{
int seed = rand();
Out << seed << std::endl;
for(int i = 0; i < records; i++)
{
Out << name[i] << std::endl;
Out << School[rand() % 6 ] << std:endl; // select a random school
Out << (rand() % 10) << std::endl; // select a random number of ounces between 0-10
Out << Entree[rand() % 3 ] << std::endl; // select random entree
Out << Dessert[rand() % 2 ] << std::endl; // select random dessert
}
Out << "Done" << std::endl;
}
void randomizeNames(string *arrayOfNames, const int arraySize)
{
std::string hold;
int randomPosition;
for(int i = 0; i < arraySize; i++)
{
randomPosition = rand() % arraySize;
hold = arrayOfNames[i];
arrayOfNames[i] = arrayOfNames[randomPosition];
arrayOfNames[randomPosition] = hold;
}
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。