当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ strtoumax()用法及代码示例


C++中的strtoumax()函数将字符串的内容解释为指定基数的整数,并将其值作为uintmax_t(最大宽度无符号整数)返回。此函数还设置一个结束指针,该指针指向字符串的最后一个有效数字字符之后的第一个字符,如果没有这样的字符,则将指针设置为null。当输入负数作为字符串时,返回值设置为垃圾值。此函数在cinttypes头文件中定义。

用法:

uintmax_t strtoumax(const char* str, char** end, int base)

参数:该函数接受三个强制性参数,如下所述:


  • str:指定由整​​数组成的字符串。
  • end:指定对char *类型的对象的引用。 end的值由函数设置为str中最后一个有效数字字符之后的下一个字符。如果不使用此参数,它也可以是空指针。
  • base:指定确定字符串中有效字符及其解释的数字基(基数)

返回类型:strtoimax()函数返回两个值,如下所述:

  • 如果发生有效转换,则该函数将转换后的整数返回为整数值。
  • 如果无法执行有效的转换,并且字符串包含带有相应整数的减号,则该函数将返回垃圾值,否则将返回零值(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


相关用法


注:本文由纯净天空筛选整理自Aman Goyal 2大神的英文原创作品 strtoumax() function in C++。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。