當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。