这个 strtoumax() C++中的函数将字符串的内容解释为指定基的整数,并将其值作为UnTimax(最大宽度无符号整数)返回。此函数还设置一个结束指针,该指针指向字符串最后一个有效数字字符后的第一个字符,如果没有这样的字符,则指针设置为null。当以字符串形式输入负数时,返回值设置为垃圾值。此函数在中定义 cinttypes 头文件。
null
语法:
uintmax_t strtoumax(const char* str, char** end, int base)
参数: 该函数接受三个强制性参数,如下所述:
- str: 指定由整数组成的字符串。
- 完: 指定对char*类型对象的引用。end的值由函数设置为str中最后一个有效数字字符之后的下一个字符。如果不使用,此参数也可以是空指针。
- 基数: 指定用于确定字符串中有效字符及其解释的基数(基数)
返回类型: 函数的作用是:返回以下两个值:
- 如果发生有效转换,则函数将转换后的整数作为整数值返回。
- 如果无法执行有效的转换,并且字符串包含带有相应整数的减号,则函数将返回垃圾值,否则将返回零值(0)
以下程序说明了上述功能:
项目1:
// C++ program to illustrate the // strtoumax() function #include <iostream> #include<cinttypes> #include<cstring> using namespace std; // Driver code int main() { int base = 10; char str[] = "999999abcdefg" ; char * end; uintmax_t num; num = strtoumax(str, &end, base); cout << "Given String = " << str << endl; cout << "Number with base 10 in string " << num << endl; cout << "End String points to " << end << endl << endl; // in this case the end pointer points to null // here base change to char16 base = 2; strcpy (str, "10010" ); cout << "Given String = " << str << endl; num = strtoumax(str, &end, base); cout << "Number with base 2 in string " << num << endl; if (*end) { cout << end; } else { cout << "Null pointer" ; } return 0; } |
输出:
Given String = 999999abcdefg Number with base 10 in string 999999 End String points to abcdefg Given String = 10010 Number with base 2 in string 18 Null pointer
项目2:
// C++ program to illustrate the // strtoumax() function #include <iostream> #include<cinttypes> #include<cstring> using namespace std; // Driver code int main() { int base = 10; char str[] = "-10000" ; char * end; uintmax_t num; // if negative value is converted then it gives garbage value num = strtoumax(str, &end, base); cout << "Given String = " << str << endl; cout << "Garbage value stored in num " << num << endl; if (*end) { cout << "End String points to " << end; } else { cout << "Null pointer" << endl << endl; } // in this case no numeric character is there // so the function returns 0 base = 10; strcpy (str, "abcd" ); cout << "Given String = " << str << endl; num = strtoumax(str, &end, base); cout << "Number with base 10 in string " << num << endl; if (*end) { cout << "End String points to " << end; } else { cout << "Null pointer" ; } return 0; } |
输出:
Given String = -10000 Garbage value stored in num 18446744073709541616 Null pointer Given String = abcd Number with base 10 in string 0 End String points to abcd
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END