c++ - 它有效,直到我输入第二个输入然后它关闭

标签 c++ codeblocks

 #include <iostream>


using namespace std;

int main()
{   int a;
    int b;
    int sum;
    string ans = "";
    cout << "Input a directive. Upon it finishing it will terminate. Codes are: \n Calc \n Exit \n";
    cin >> ans;
    if(ans == "Calc")
    {
        cout << "Welcome to Calculator! Put in a number. Press Enter to put in number. \n";
        cin >> a;

        cout << "Next number \n";
        cin >> b;
        sum = a + b;

        cout << sum << " Is the amount! \n";
        cout << "Input a directive. Upon it finishing it will terminate. Codes are: \n Calc \n Exit \n";
        ans = "";    
    }

    if(ans != "Calc")
    {    
        cout << "Okay";    
    }
}

这行得通,但如果我不输入 Calc,它什么都不做,但打印出来,但如果我不再输入 Calc,它就会关闭。如果我确实输入了计算器,我可以运行它,当它给出答案时,没问题,然后我按任意键它就关闭了。我是这个论坛/网站的新手,不确定位置是否正确。

最佳答案

好吧,如果你想让程序再次接受用户的输入,那么你应该这样写:

#include <iostream>
using namespace std;
int main()
{   int a;
    int b;
    int sum;
    while(true) 
    {
         string ans = "";
         cout << "Input a directive. Upon it finishing it will terminate. Codes are: \n Calc \n Exit \n";
         cin >> ans;
         if(ans == "Calc")
         {
             cout << "Welcome to Calculator! Put in a number. Press Enter to put in number. \n";
             cin >> a;

             cout << "Next number \n";
             cin >> b;
              sum = a + b;

              cout << sum << " Is the amount! \n";
          }
          else if(ans == "Exit") 
          {
              cout << "Bye!\n";    
              return 0;
          }
          cout << "Okay\n";    
     }
}

关于c++ - 它有效,直到我输入第二个输入然后它关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22828101/

相关文章:

c++ - 了解预处理器指令

c++ - KeyPressEvent 不起作用

c - 打开文件会导致程序出现段错误

c++ - 通过选择 'Quit' 菜单项关闭应用程序 - wxWidgets 3.0

c++ - 与 MinGW 4.7.1 上的 -static-libstdc++ 标志链接

c++ - Qt GUI - 仅当值更改时才想从 .txt 文件中读取

c++ - 难以定位 for 循环中的问题

c - C编程中如何检查输入是否等于预设值?

c++ - 使用 freeglut 编译问题

c++ - 用给定的线段数逼近圆