从输入文件

时间:2016-04-26 21:50:43

标签: c++ fstream

我需要创建一个包含输入文件中4列单词的程序。

enter image description here

然后从每列中随机选择一个单词并生成一个句子。最终目标是将对话保存到输出文件中。

enter image description here

我已经创建了读取输入文件的代码,并打开输出文件进行写入,但我不知道如何从列中选择一个单词并创建句子,我猜是使用数组会工作,但我不确定如何将它与文件连接?

#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>

using namespace std;

int main()
{
    string ifilename, ofilename, line;
    ifstream inFile, checkOutFile;
    ofstream outFile;
    char response;

    // Input file
    cout << "Please enter the name of the file you wish to open : ";
    cin >> ifilename;
    inFile.open(ifilename.c_str());
    if (inFile.fail())
    {
        cout << "The file " << ifilename << " was not successfully opened." << endl;
        cout << "Please check the path and name of the file. " << endl;
        exit(1);
    }
    else
    {
        cout << "The file is successfully opened." << endl;
    }

    // Output file

    cout << "Please enter the name of the file you wish to write : ";
    cin >> ofilename;

    checkOutFile.open(ofilename.c_str());

    if (!checkOutFile.fail())
    {
        cout << "A file " << ofilename << " exists.\nDo you want to continue and overwrite it? (y/n) : ";
        cin >> response;
        if (tolower(response) == 'n')
        {
            cout << "The existing file will not be overwritten. " << endl;
            exit(1);
        }
    }

    outFile.open(ofilename.c_str());
    if (outFile.fail())
    {
        cout << "The file " << ofilename << " was not successfully opened." << endl;
        cout << "Please check the path and name of the file. " << endl;
        exit(1);
    }
    else
    {
        cout << "The file is successfully opened." << endl;
    }

    // Copy file contents from inFile to outFile

    cout << "Hi, what's up? " << endl; // Pre-set opener

    while (getline(inFile, line))
    {

        cout << line << endl;
        outFile << line << endl;
    }

    // Close files
    inFile.close();
    outFile.close();
} // main

1 个答案:

答案 0 :(得分:0)

您可以使用字符串的2D矢量来存储句子的单词,并使用rand之类的随机数生成器从每列中选择特定的行元素。类似于以下内容

vector<vector<string>> myConversationVector;
while (choice != "no")
{
    std::cout << myConversationVector[rand() % 5][0]  <<" "
              << myConversationVector[rand() % 5][1]  <<" "
              << myConversationVector[rand() % 5][2]  <<" "
              << myConversationVector[rand() % 5][3];

}