C++字符串转换(stoi;stol;stoul;stoll;stoull;stof;stod;stold)

1、C/C++:long int与long long的区别

在实际的使用中,long与int几乎没有区别:原因是早期的C编译器定义了long int占用4个字节,int占用2个字节,long int是名副其实的长整型。在ANSI C的标准中,对长整型的定义也是long int应该至少和int一样长,而不是long int 一定要比int占用存储字节长。

2、stoi

int stoi (const string&  str, size_t* idx = 0, int base = 10);
int stoi (const wstring& str, size_t* idx = 0, int base = 10);
  1. 将字符串转换为整数

    解析str将其内容解释为指定基数的整数,并以int值的形式返回。

    如果idx不是空指针,则该函数还将idx的值设置为数字后str中第一个字符的位置。

    该函数使用strtol(或wcstol)来执行转换(有关该过程的更多详细信息,请参阅strtol)

  2. 参数

    str:字符串对象,表示整数。
    idx:指向size_t类型对象的指针,其值由函数设置为数值后str中下一个字符的位置。此参数也可以是空指针,在这种情况下不使用它。
    base:确定有效字符及其解释的数字基数(基数)。如果为0,则使用的基数由序列中的格式确定(有关详细信息,请参阅strtol)。 请注意,默认情况下,此参数为10,而不是0。

    参数base范围从2至36,或0。参数base代表采用的进制方式,如base值为10则采用10进制,若base值为16则采用16进制等。当base值为0时则是采用10进制做转换,但遇到如’0x’前置字符则会使用16进制做转换、遇到’0’前置字符而不是’0x’的时候会使用8进制做转换。

  3. 返回值

    成功时,该函数将转换后的整数作为int值返回。

注意:转化过程种容易出现错误导致程序崩溃。最好加上异常处理
如果无法执行转换,则抛出invalid_argument异常。
如果读取的值超出int的可表示值范围,则抛出out_of_range异常。
无效的idx会导致未定义的行为。

3、stol

解析str将其内容解释为指定基数的整数,并以long int类型的值返回。

long stol (const string&  str, size_t* idx = 0, int base = 10);
long stol (const wstring& str, size_t* idx = 0, int base = 10);

4、stoul

解析str将其内容解释为指定基数的整数,该基数作为无符号长整数值返回。

unsigned long stoul (const string&  str, size_t* idx = 0, int base = 10);
unsigned long stoul (const wstring& str, size_t* idx = 0, int base = 10);

5、stoll

解析str将其内容解释为指定基数的整数,并将其作为long long类型的值返回。

long long stoll (const string&  str, size_t* idx = 0, int base = 10);
long long stoll (const wstring& str, size_t* idx = 0, int base = 10);

6、stoull

解析str将其内容解释为指定基数的整数,该值作为unsigned long long类型的值返回。

unsigned long long stoull (const string&  str, size_t* idx = 0, int base = 10);
unsigned long long stoull (const wstring& str, size_t* idx = 0, int base = 10);

7、stof

解析str将其内容解释为浮点数,该值作为float类型返回。

float stof (const string&  str, size_t* idx = 0);
float stof (const wstring& str, size_t* idx = 0);

8、stod

解析str将其内容解释为浮点数,该值返回为double类型的值。

double stod (const string&  str, size_t* idx = 0);
double stod (const wstring& str, size_t* idx = 0);

9、stold

将字符串转换为long double

long double stold (const string&  str, size_t* idx = 0);
long double stold (const wstring& str, size_t* idx = 0);

参考:(9条消息) C++字符串转换(stoi;stol;stoul;stoll;stoull;stof;stod;stold)_WilliamX2020的博客-CSDN博客_stoul

posted @ 2022-09-06 10:04  hiccup_lh  阅读(624)  评论(0编辑  收藏  举报