我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确

im trying to make a program that ask the user to enter a question and answer, but the program does not loop right

本文关键字:程序 问题 输入 用户 答案 不正确 循环 一个      更新时间:2023-10-16

我正在进行一个项目,要求用户创建一个问答。然后程序将询问用户是否要添加更多问题。由于某种原因,我的程序没有循环。这是我的密码。如果有什么建议,请告诉我。谢谢

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

编辑我添加了整个代码。

应删除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");
}

尝试将问题和答案连接到单个字符串中的方式将不起作用,它们将被调用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::向量中,该向量将在最后写入文件。只是想一想:-(