я пытаюсь сделать программу, которая просит пользователя ввести вопрос и ответ, но программа не работает правильно - PullRequest
0 голосов
/ 27 октября 2018

Я работаю над проектом, в котором я прошу пользователя создать вопрос и ответ. Затем программа спросит пользователя, нужно ли ему добавить дополнительные вопросы. По какой-то причине моя программа не зацикливается. вот мой код если есть какие-либо предложения, пожалуйста, дайте мне знать. спасибо.

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

using namespace std;

int main()
{
    string exam_Name;
    string questions, DMV, answer;
    fstream examfile;
    string another_question,no,yes;

    examfile.open("exam.txt");
    // ask the user to create a question

    while (another_question != "no");
    {
        cout << "create a question. " << endl;
        getline(cin, questions);
        cout << "enter the answer" << endl;
        getline(cin, answer);
        // program will now ask the user to create another question
        cout << "would you like to add another question, yes or no ?" << endl;
        getline(cin, another_question);
    }

    //display question and answer on the document
    examfile << questions << endl;
    examfile << answer;

    return 0;
    system("pause");
}

Ответы [ 2 ]

0 голосов
/ 27 октября 2018

То, как вы пытаетесь объединить вопросы и ответы в отдельные строки, не будет работать, они будут перезаписаны с помощью вызова getline ().

while (another_question != "no");

Приведенная выше строка считается плохой практикой, вы должны использоватьболее подходящий тип как условие цикла, а также точка с запятой.

Вот пример кода, который намного лучше и даст желаемые результаты.

    // You want to append any changes to the file, for example
    // in the case of re-using the program.
    File.open( "exam.txt", std::ios::app );

    while( AnotherQuestion ) {
        printf( "Please enter a question:\n" );
        std::getline( std::cin, Buffer );
        File << Buffer << std::endl;

        printf( "Please enter an answer:\n" );
        std::getline( std::cin, Buffer );
        File << Buffer << std::endl;

        printf( "Would you like to add another question? (Yes/No)\n" );
        std::getline( std::cin, Buffer );

        // You want to be able to receive input regardless of case.
        std::transform( Buffer.begin( ), Buffer.end( ), Buffer.begin( ), ::tolower );
        AnotherQuestion = Buffer.find( "yes" ) != std::string::npos;
    }

Другой подход, который вы можете использовать, - создать класс, содержащий вопросы и ответы, а затем сохранить входные данные в std :: vector, который будет записан в файл в конце.Просто о чем подумать: -)

0 голосов
/ 27 октября 2018

Редактировать Я добавил весь код.


; сразу после удаления оператора while.То есть, поскольку

while (another_question != "no");

является бесконечным циклом и никогда не заканчивается, мы должны переписать эту строку следующим образом:

while (another_question != "no")

Я хочу показать все вопросы

Поместив examfile << в раздел while{...}, вы можете показать все вопросы:

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

using namespace std;

int main()
{
    string questions, answer;
    fstream examfile;
    string another_question;

    examfile.open("exam.txt");
    // ask the user to create a question

    while (another_question != "no");
    {
        cout << "create a question. " << endl;
        getline(cin, questions);
        cout << "enter the answer" << endl;
        getline(cin, answer);

        //display question and answer on the document
        examfile << questions << endl;
        examfile << answer << endl;

        // program will now ask the user to create another question
        cout << "would you like to add another question, yes or no ?" << endl;
        getline(cin, another_question);
    }

    return 0;
    system("pause");
}
...