C ++ while(true)vs while(!something)

时间:2018-10-27 14:23:05

标签: c++ do-while

因此,假设我们有一些代码,我们希望用户说一些特定的东西,但是如果他们弄错了,我们希望给他们无限的尝试。我会使用#if defined ( _WIN32 ) #include <sys/stat.h> #endif std::time_t GetFileWriteTime ( const std::filesystem::path& filename ) { #if defined ( _WIN32 ) { struct _stat64 fileInfo; if ( _wstati64 ( filename.wstring ().c_str (), &fileInfo ) != 0 ) { throw std::runtime_error ( "Failed to get last write time." ); } return fileInfo.st_mtime; } #else { auto fsTime = std::filesystem::last_write_time ( filename ); return decltype ( fsTime )::clock::to_time_t ( fsTime ); } #endif } 循环。

do while

但是,有人告诉我,使用#include <iostream> #include <string> int main() { std::string input; std::cout<<"Enter yes or no: "; do { std::cin>>input; if (input == "yes") { break; } else if (input == "no") { break; } else { std::cout<<std::endl<<"Enter yes or no: "; } } while (true); } 是不好的做法,而且,(在这种情况下)我应该改为使用while (true);。其中哪一个是正确的?

while (input != "yes" && input != "no");

1 个答案:

答案 0 :(得分:0)

该循环应测试输入失败(您忘记了),然后测试是否必须循环。因此,应该是:

{
  "EN": {
    "name": "Name",
    "surname": "Surname"
  },
  "AL": {
    "name": "Emri",
    "surname": "Mbiemri"
  },
  "MK": {
    "name": "Име",
    "surname": "Презиме"
  }
}

当您不需要显式刷新时,不应使用while ((std::cin >> input) && input != "yes" && input != "no") std::cout << "\nEnter yes or no: ";

或者更好的是,将其封装在可重用的函数中,并在输入失败时引发异常。

相关问题