代码之家  ›  专栏  ›  技术社区  ›  Mike Ericson

Do While要求用户重复整个int主程序

  •  -5
  • Mike Ericson  · 技术社区  · 11 年前

    编程很新,我在网上找不到任何基本的解释,也找不到适合我需要的代码。我有一个相当长的程序(大约300行),它都能工作。这是给出一个想法的结构:

    #include <iostream>   
    #include <stdlib.h>    
    #include <time.h>      
    #include <vector>      
    #include <algorithm>   
    
    using namespace std;   
    
    int main() 
    {
          //code....
    
        { 
             //code... etc...
        }
    
    }
    

    我想请用户重复该程序。如果输入y,则重复int main,直到再次提出相同的重复问题。除此之外&书信电报;“例如,谢谢,再见”;

    3 回复  |  直到 11 年前
        1
  •  2
  •   user2970916    11 年前
    #include <iostream>   
    #include <stdlib.h>    
    #include <time.h>      
    #include <vector>      
    #include <algorithm>   
    
    //using namespace std;   <--- Don't use using namespace std, it pollutes the namespace
    
    void repeat()
    {
       //... code to repeat
    }
    
    int main() 
    {
          //code....
        char answer;
        while((std::cin >> answer) != 'y')
        { 
            repeat();
        }
    }
    
        2
  •  2
  •   Sheryar Khan    6 年前
    #include <iostream>
    #include <conio.h>
    
    using namespace std;
    
    //Class
    class DollarToRs {
      public:
    
          int Dollar;
          int Rs;
          int ToRs;
          ConversionToRs() {
          cout << "Enter the amount of Dollar: ";
          cin >> Dollar;
          ToRs = Dollar * 154;
          cout << "This is the total amount in PKR: " << ToRs <<endl;
          }
    
    };
    
    int main()
    {
      //Dollar Convertion Function
      DollarToRs convert;
      convert.ConversionToRs();
    
    
      //For Repeating Program
    
      int repeat;
      int exit;
    
      cout << "To repeat program enter 1" <<endl;
      cin >> repeat;
    
      while (repeat == 1) {
        convert.ConversionToRs();
        cout << "To repeat program enter 1" <<endl;
        cin >> repeat;
      }
      exit =0;
    
      if (exit == 0) {
    
      }
    
      getch();
      return 0;
    }
    
        3
  •  1
  •   Emil Laine    11 年前

    下面是一个简单解决方案的示例:

    int main()
    {
        for (;;) // "infinite" loop (while (true) is also possible)
        {
            // stuff to be repeated here
    
            cout << "Repeat? [y/n]" << endl;
            char answer;
            cin >> answer;
            if (answer == 'n')
                break; // exit loop
        }              // else repeat
        cout << "Thank you, goodbye" << endl;
    }
    

    还有一个:

    int main()
    {
        bool repeat = true;
        while (repeat)
        {
            // stuff to be repeated here
    
            cout << "Repeat? [y/n]" << endl;
            char answer;
            cin >> answer;
            repeat = answer == 'y';
        }
        cout << "Thank you, goodbye" << endl;
    }
    

    作为补充说明,不要这样做: #include <stdlib.h> .在C++中,应该使用 c 使用C头文件时使用前缀头文件名: #include <cstdlib> #include <ctime> .