C++ While 循环工作

C++ While Loop to work

因为我知道 Python (3) 的基础知识,所以我决定把我在 Python 中编写的程序用 C++ 键入它们以掌握 C++ 的窍门。

问题:当您键入 "TheEnd" 作为名称时,我希望程序结束,但出于某种原因,如果您键入 "TheEnd" 它会其他字段求一次,然后结束。 有没有办法让用户在要求输入名称时键入 "TheEnd" 而程序刚刚结束?(我尝试将 while 循环放在不同的区域,但无济于事.)

这是我的资料:

#include <iostream>
#include <string>

//While loop.

using namespace std;

main()
{

   string name;
   string major;
   float hours, qualityPoints, GPA;

   while (name!="TheEnd") //Here's the while loop

   {
   cout<<"Please enter your name. "<<endl;
   cin>>name;

   cout<<"Please enter your major. "<<endl;
   cin>>major;

   cout<<"List the hours you've completed so far. "<<endl;
   cin>>hours;

   cout<<"List how many quality points you have. "<<endl;
   cin>>qualityPoints;

   GPA = qualityPoints / hours;

   if (GPA >= 3.4 and hours >= 12)

   {

   cout<<name<<endl;
   cout<<major<<endl;
   cout<<"You made the Dean's List."<<endl;
   }

   else

   {

   cout<<"You did not make the Dean's List."<<endl;

   }
}

}

是问,因为你的条件是一开始就测试,然后问完所有字段。

代码的最小变化是以下变化:

 for(;;) // Former while(name!="TheEnd")
 {
   cout<<"Please enter your name. "<<endl;
   cin>>name;

   if(name=="TheEnd")
       break;

一些解释:

通常使用for(;;)而不是while(true)作为无限循环是常见的做法。其原因在于某些编译器会针对 if/while 中的常量表达式发出(ted)警告(例如 VS 2005 被 AFAIK 广泛使用)。在大多数专业项目中,警告被视为错误。

每个循环 (for/while) 都可以使用 break 退出。所以你没有循环条件,只有退出条件。我决定编写这个解决方案,因为它需要对您的示例代码进行最小的更改。也没有(简单的)方法可以让你的中断条件成为 while 条件的一部分。

保留 while(name!="TheEnd") 并仅在 cin 之后添加 if 是不好的做法。你用那个生成“货物崇拜编程”代码。