首页 > 解决方案 > 我试图制作一个要求用户输入问题和答案的程序,但程序没有正确循环

问题描述

我正在做一个项目,我要求用户创建一个问题和答案。然后程序会询问用户是否要添加更多问题。出于某种原因,我的程序没有循环。这是我的代码。如果有任何建议,请告诉我。谢谢。

#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");
}

标签: c++fileloopswhile-loop

解决方案


编辑我添加了整个代码。


;刚刚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");
}

推荐阅读