c++中如何将string中数字转换成整型的

如题,举例说明才给分(还有腾讯 我的问题到底是哪里审核不过 老和我过不去)

1、方法一:c++11中string中添加了下面这些方法帮助完成字符串和数字的相互转换。

#include <iostream>#include <string>using namespace std;int main() {
cout << stof("123.0") <<endl;
size_t pos;
cout << stof("123.01sjfkldsafj",&pos) <<endl;
cout << pos << endl;
cout << to_string(123.0) << endl;    return 0;
}

2、方法二:C++中使用字符串流stringstream来做类型转化。

#include <iostream>#include <string>#include <sstream>using namespace std;int main() {
ostringstream os;    float fval = 123.0;
os << fval;
cout << os.str() << endl;

istringstream is("123.01");    is >> fval;
cout << fval << endl;    return 0;
}

3、可以用sprintf函数将数字转换成字符串。

 int H, M, S;

     string time_str;

     H=seconds/3600;

     M=(seconds%3600)/60;

     S=(seconds%3600)%60;

     char ctime[10];

     sprintf(ctime, "%d:%d:%d", H, M, S); // 将整数转换成字符串

     time_str=ctime; // 结果

温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-07-25

代码如下:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string STRING;
    int INT;
    cin >> STRING;
    if(cin)
    {
        INT = stoi(STRING);
        cout << INT << endl;
    }
    else
        cout << "An unknown error occurred." << endl;
    return 0;
}

关键代码在第12行

如果输入的字符串前几个是数字,后面紧跟着的第一个字符是非数字字符,那么往后所有的字符直接舍弃;如果刚开始就不是数字,那么会抛出异常。(throw invalid_argument)

第2个回答  2017-06-26

方法有很多

其中一种是使用C++中的流

    声明字符串

    声明流

    字符串输出到流

    流输出到数字

    打印数字

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
   string str="6666";//声明变量
   stringstream ss;//声明流
   ss<<str;    //字符串输出流
   int nums;
   ss>>nums;    //输入到数字
   cout<<nums<<endl; //打印
}

第3个回答  2017-08-01
1.使用C语言的atoi,strtol函数(stdlib.h头文件)int x=atoi(string("12365").c_str());2.使用stringstream(需包含sstream头文件) int x;string str="123";stringstream stream;stream<<str;stream>>x;cout<<x<<endl;
第4个回答  2013-08-08
利用atoi函数即可,如下:string s = "123";int x = atoi(s.c_str());
相似回答