strtoul 是一个C语言库函数,用于将字符串转换为无符号长整数
stdlib.h 头文件以使用 strtoul 函数。#include <stdlib.h>编写验证函数:创建一个函数,接收一个字符串参数,并使用 strtoul 进行验证。#include<stdio.h>#include <stdbool.h>#include <ctype.h>bool is_valid_number(const char *str) { if (str == NULL || *str == '\0') { return false; } char *endptr; strtoul(str, &endptr, 10); // 如果endptr指向字符串末尾,说明整个字符串都是有效数字 return *endptr == '\0';}测试验证函数:编写测试代码来验证你的函数是否正确。int main() { const char *test1 = "12345"; const char *test2 = "-12345"; const char *test3 = "12a45"; const char *test4 = ""; const char *test5 = NULL; printf("Test 1: %s\n", is_valid_number(test1) ? "Valid" : "Invalid"); printf("Test 2: %s\n", is_valid_number(test2) ? "Valid" : "Invalid"); printf("Test 3: %s\n", is_valid_number(test3) ? "Valid" : "Invalid"); printf("Test 4: %s\n", is_valid_number(test4) ? "Valid" : "Invalid"); printf("Test 5: %s\n", is_valid_number(test5) ? "Valid" : "Invalid"); return 0;}这个示例中的 is_valid_number 函数会返回 true,如果给定的字符串表示一个有效的无符号整数。通过使用 strtoul 函数,我们可以轻松地检查字符串是否只包含数字并且没有其他无效字符。


