c++ - 再次提示运行程序: fixing if they put an invalid statement in

标签 c++

早上好!

我的问题:我在程序中声明输入 Y 表示是,N 表示否。如果用户输入是、否或随机字符串,它会说这是无效输入并再次询问。但假设用户输入“yes yes yes”,则会输出3次无效语句。我该如何解决这个问题?

我还需要对 bool 值做一些事情,因为它没有任何作用,因为如果他们说 n,我就会中断循环,但没关系。

这是我的代码片段:

bool done = true;
string ans;

try {
   coeff input = readCoeffs();
   results result = equSolver(input);
   outResults(input, result);

   while (done == true) {
      cout << "Would you like to run the program again (Y to run again, N to close)? ";
      cin >> ans;
         if (ans == "Y" || ans == "y") {
            coeff input = readCoeffs();
            results result = equSolver(input);
            outResults(input, result);
         }
         else if (ans == "N" || ans == "n") break;
         else cout << "Invalid input. \n";
   }
}

catch (const char* msg) {
   cerr << msg << endl;
}

最佳答案

应该是

while(done == false)

Done 应该初始化为 false,并且在循环中,当输入 N 或 n 时将 did 设置为 true。这在某种程度上是一个风格问题,但通常最好避免中断,除非有非常充分的理由。

对于您的无效输入问题,您正在使用

cin >> ans;

这被空格打破了,所以输入“l m no p”将使程序说两次“无效输入”,然后退出。如果您想按行处理,请考虑使用 getline。

关于c++ - 再次提示运行程序: fixing if they put an invalid statement in,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21761150/

相关文章:

C++ 程序不会使用此处不允许的预期表达式和函数进行编译

c++ - 如何正确地将输出组织成列?

c++ - C++ 中 seekp(...) 的奇怪行为

c++ - 合并一个 vc++ 和一个 c++ 构建器项目

C++ 相同的字符串不相等(实际上是 char*)

c++ - WinCE6.0或DMA实现中的多重处理

c++ - AWS C++ 开发工具包 UploadPart 超时

c++ - 在 unix 上用 c++ 写一个空的 iso 图像

c++ - Visual Studio 2010 和 std::function

C++11 标准决定 "shared_ptr(const weak_ptr<Y>& r) Throws bad_weak_ptr"