溫馨提示×

C++ strtol的邊界條件測試技巧

c++
小樊
82
2024-07-12 13:45:28
欄目: 編程語言

在測試strtol函數(shù)的邊界條件時,通??梢钥紤]以下幾種情況:

  1. 輸入字符串為空字符串或只包含空格字符。
  2. 輸入字符串代表的數(shù)字小于LONG_MIN或大于LONG_MAX。
  3. 輸入字符串超過LONG_MAX或小于LONG_MIN的情況。
  4. 輸入字符串包含非數(shù)字字符或非法字符。
  5. 輸入字符串包含正負(fù)號。
  6. 輸入字符串包含前導(dǎo)空格或后導(dǎo)空格。

以下是一個簡單的測試代碼示例:

#include <iostream>
#include <cstdlib>
#include <climits>

int main() {
    const char *str = "12345";
    char *endptr;
    long num = strtol(str, &endptr, 10);

    if ((num == LONG_MIN || num == LONG_MAX) && errno == ERANGE) {
        std::cout << "Overflow or underflow detected" << std::endl;
    } else if (*endptr != '\0' && *endptr != ' ') {
        std::cout << "Invalid character found in input" << std::endl;
    } else {
        std::cout << "Parsed number: " << num << std::endl;
    }

    return 0;
}

在此示例中,我們測試了數(shù)字范圍是否在LONG_MINLONG_MAX之間,以及是否有非法字符和空格。您可以根據(jù)具體需求和情況擴(kuò)展測試用例。

0