当前位置:Gxlcms > mysql > 技巧:巧用数组减少if语句

技巧:巧用数组减少if语句

时间:2021-07-01 10:21:17 帮助过:35人阅读

/* * FileName: odd_or_even.cpp * Author: Antigloss at http://stdcpp.cn * LastModifiedDate: 2005-7-22 22:30 * Purpose: Tell if a given number is odd or even */ #include cstdlib // for EXIT_SUCCESS #include iostream #include limits // for nu

/*
* FileName: odd_or_even.cpp
* Author: Antigloss at http://stdcpp.cn
* LastModifiedDate: 2005-7-22 22:30
* Purpose: Tell if a given number is odd or even
*/

#include // for EXIT_SUCCESS
#include
#include // for numeric_limits

// flush the input buffer
inline void flush_stdin()
{
std::cin.clear(); // clear error state of the stream
// clear data left at the input buffer
std::cin.ignore( std::numeric_limits< std::streamsize >::max(), '\n' );
} // end of flush_stdin

int main()
{
long num;
const char *msg[] = { "Even", "Odd" };

for (;;) {
std::cout << "Please input an integer(q to end): ";

if ( std::cin >> num ) {
std::cout << msg[num & 1L] << '\n'; // we can also use `num % 2L'
} else {
std::cin.clear(); // clear error state before reading from the input stream
if ( std::cin.get() == 'q' ) {
flush_stdin();
break;
}
std::cerr << "You should input an INTEGER!\n";
}
flush_stdin();
}

std::cout << "Thanks for using our product!\nPress ENTER to quit...";
std::cin.get();
return EXIT_SUCCESS;
}

人气教程排行