对于练习,我正在编写一个程序,从用户那里获取有关他们所学课程的数据,最后将这些数据输出到一个整洁的成绩单文件中,并带有一系列计算,如GPA,总计单位等。
我正在使用do-while loop
,但它似乎无法正常工作。
我认为问题在于addClass
变量,因为即使我指定它只询问另一个类addClass = 1
,它仍然会在我输入0时请求。有没有人有更多经验有解决方案吗?谢谢。
//Prog: Unofficial Transcript Creator
//Modified 5-08-2018
#include<iostream>
#include<iomanip>
#include<cmath>
#include<fstream>
#include<string>
using namespace std;
int main() {
//Declares.
string classSubject;
int classCode;
string professorFirst, professorLast;
int classUnits;
string grade;
int addClass;
ofstream fout;
//Open the output file.
fout.open("UNOFFICIAL_TRANSCRIPT.TXT");
//Test if the file opened.
if (fout) {
cout << "The output file has been located. Please begin input of transcript data." << endl;
cout << endl;
}
else
cout << "ERROR ID107: The output file was not found. Please create a blank text document named UNOFFICIAL_TRANSCRIPT.TXT.";
//Prompt user for information.
do {
addClass = 0;
cout << "Please enter the class subject: ";
cin >> classSubject;
cout << endl;
cout << "Please enter the class code: ";
cin >> classCode;
cout << endl;
cout << "Please enter the first name of the professor: ";
cin >> professorFirst;
cout << endl;
cout << "Please enter the last name of the professor: ";
cin >> professorLast;
cout << endl;
cout << "How many units is the class worth? ";
cin >> classUnits;
cout << endl;
cout << "What grade did you get in the class? ";
cin >> grade;
cout << endl;
cout << "Would you like to add another class? Type 1 for yes or 0 for no. ";
cin >> addClass;
cout << endl;
fout << setw(12) << classSubject << classCode;
}
while
(addClass = 1);
system("pause");
return 0;
}
答案 0 :(得分:2)
将while(addClass = 1 )
替换为while(addClass == 1)
。
前者将值1分配给addClass,然后检查表达式的值(指定的值,即1)是否为非零。 由于此值不为零,因此您的循环永远无法退出循环。
后者执行相等性检查以查看addClass
的值是否等于1.
恕我直言,while (addClass = 1)
也应该对任何体面的编译器发出警告(特别是如果所有警告都已启用),因为这是一个非常常见的错误/错字。
另外,如果它不是拼写错误,那么现在是刷新C ++基础知识的好时机。