📜  C++中的strtoumax()函数

📅  最后修改于: 2021-05-30 10:25:29             🧑  作者: Mango

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

句法:

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

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

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

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

  • 如果发生有效转换,则该函数将转换后的整数返回为整数值。
  • 如果没有有效的转换可以进行并该字符串是否包括与相应的整数,则垃圾值由否则返回零值的函数返回减号(0)

下面的程序说明了上述函数:

程序1:

// C++ program to illustrate the
// strtoumax() function
#include 
#include
#include
  
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 
#include
#include
  
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
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。