c++ 字符串和数字转换时的特殊处理

基本用法

代表数字的string如何转化为对应的数字?使用 atoi() 函数。下面是具体写法:

#include <iostream>
#include <stdlib.h>  //atoi和atof对应的头文件
#include <string>

using namespace std;

int main(){
    string a = "5";
    cout << atoi(a.c_str()) << endl;

    //输出结果为 5
    return 0;
}

特殊情况

上面的例子只是给出了一个最基本的情况,即我们需要转化的string是一个整数。

一般的,我们可能会希望对一些代表浮点数的字符串进行转化,这时可以用和atoi()长得很类似的一个函数atof()

这两个函数都可以处理浮点数型的string,然而结果可能不同,具体结果如下所示。

#include <iostream>
#include <stdlib.h>
#include <typeinfo>
#include <string>
using namespace std;

int main(){
    string a = "5";
    string b = "5.0";
    string c = "5.5";

    cout << atoi(a.c_str()) << endl;
    cout << atoi(b.c_str()) << endl;
    cout << atoi(c.c_str()) << endl;
    cout << atof(a.c_str()) << endl;
    cout << atof(b.c_str()) << endl;
    cout << atof(c.c_str()) << endl;

    cout << typeid(atoi(a.c_str())).name() << endl;
    cout << typeid(atoi(b.c_str())).name() << endl;
    cout << typeid(atoi(c.c_str())).name() << endl;
    cout << typeid(atof(a.c_str())).name() << endl;
    cout << typeid(atof(b.c_str())).name() << endl;
    cout << typeid(atof(c.c_str())).name() << endl;

    return 0;
}

输出结果如下:

c++ 字符串和数字转换时的特殊处理

可以注意到:

对于atoi()函数来说,不论输入的string是否是一个浮点数,都会将小数点之后的抹去,输出一个整数;而对于atof()函数来说,如果是5.0这样的数,也自动会将小数点及后面的0消去。

尽管你可能会担心atof()这个自动消去.0的操作会将输出的数字变为一个整型数,然而事实上,通过typeid()查看输出类型可知,atoi()输出的一定是int型的数据,而atof()输出的一定是double型的数据。

原文链接: https://www.cnblogs.com/fyunaru/p/12879701.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    c++ 字符串和数字转换时的特殊处理

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/348017

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午4:50
下一篇 2023年3月2日 上午4:50

相关推荐