C++程式設計易錯和錯誤檢查
阿新 • • 發佈:2020-12-22
1.輸入錯誤
If the user has entered invalid input, ask the user to enter the input again.
#include <iostream>
#include <limits>
#include <string>
int main()
{
std::string hello{ "Hello, world!" };
int index;
do
{
std::cout << "Enter an index: " ;
std::cin >> index;
//handle case where user entered a non-integer
if (std::cin.fail())
{
std::cin.clear(); // reset any error flags
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// ignore any characters in the input buffer
index = -1;
// ensure index has an invalid value so the loop doesn't terminate
continue; // this continue may seem extraneous,
// but it explicitly signals an intent to terminate this loop iteration...
}
// ...just in case we added more stuff here later
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// ignore any remaining characters in the input buffer
} while (index < 0 || index >= static_cast<int>(hello.size()));
// handle case where user entered an out of range integer
std::cout << "Letter #" << index << " is " << hello[index] << '\n';
return 0;
}
2.輸出流為NULL
Quietly skip the code that depends on the assumption being valid:
void printString(const char *cstring)
{
// Only print if cstring is non-null
if (cstring)
std::cout << cstring;
}
3.錯誤的返回值
return an error code back to the caller and let the caller deal with the problem
#include <array>
// assume the array only holds positive values
int getArrayValue(const std::array<int, 10> &array, int index)
{
// use if statement to detect violated assumption
if (index < 0 || index >= static_cast<int>(array.size()))
return -1; // return error code to caller
return array[index];
}