2016-04-26 3 views
0

Мне нужно создать программу, содержащую 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 

ответ

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]; 

} 
Смежные вопросы