开发者社区> 问答> 正文

生成文件的C++程序

因此,我试图从一个文件中读取名称,并根据我想要的名称数将其输出到另一个文件中,但是当程序运行时,就没有输出了。我正在读取一个文件“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;
    }
}

展开
收起
aqal5zs3gkqgc 2019-12-04 22:49:38 798 0
0 条回答
写回答
取消 提交回答
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
使用C++11开发PHP7扩展 立即下载
GPON Class C++ SFP O;T Transce 立即下载
GPON Class C++ SFP OLT Transce 立即下载