『写在前边』
因为写PAT总是遇到字符串(主要是String)和数值之间的转化,所以整理一下以便好复习。
『String类型的字符串』
这里数值和字符串相互转换的例子,使用的是stringstream函数,在c++11当中有定义好的现成的函数取调用,非常方便。
1.【字符串转换为数值】
string和数值转换 | 转换类型 |
---|---|
to_string(val) | 把val转换成string |
stoi(s,p,b) | 把字符串s从p开始转换成b进制的int |
stol(s,p,b) | 把字符串s从p开始转换成b进制的long |
stoul(s,p,b) | 把字符串s从p开始转换成b进制的unsigned long |
stoll(s,p,b) | 把字符串s从p开始转换成b进制的long long |
stoull(s,p,b) | 把字符串s从p开始转换成b进制的unsigned long long |
stof(s,p) | 把字符串s从p开始转换成float |
stod(s,p) | 把字符串s从p开始转换成double |
stold(s,p) | l把字符串s从p开始转换成long double |
#include <bits/stdc++.h>
#include <map>
using namespace std;
int main(){
string s="222.22";
cout<<"s="<<s<<endl;
int a = 222;
int ot = stoi(s,0,10);
int ol = stol(s,0,10);
float of = stof(s,0);
double od = stod(s,0);
cout<<"ot="<<ot<<endl;
cout<<"ol="<<ol<<endl;
cout<<"of="<<of<<endl;
cout<<"od="<<od<<endl;
return 0;
}
2.【数值转换为字符串】
用stringstream即可把多种数值类型转换为String类型的字符串
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main(){
double a = 123.32;
string res;
stringstream ss;
ss << a;
ss >> res;//或者 res = ss.str();
cout<<res;
return 0;
}
『Char数组类型的字符串』
这里是使用C语言提供了几个标准库函数,可以将任意类型(整型、长整型、浮点型等)的数字和字符串相互转换。
字符串和数值转换 | 作用 |
---|---|
atof(s) | 将字符串s[n]转换为双精度浮点型值。 |
atoi(s) | 将字符串s[n]转换为整型值。 |
atol(s) | 将字符串s[n]转换为长整型值。 |
strtod(s,*p,b) | 将字符串s[n]转换为b进制双精度浮点型值,到p停止,并报告不能被转换的所有剩余数字。 |
strtol(s,*p,b) | 将字符串s[n]转换为b进制长整值,到p停止,并报告不能被转换的所有剩余数字。 |
strtoul(s,*p,b) | 将字符串s[n]转换为b进制无符号长整型值,到p停止,并报告不能被转换的所有剩余数字。 |
#include <cctype>
#include <cstdio>
#include <cstdlib>
int main(void ) {
char s[100]="1431";
printf("The number integer is %d\n",atoi(s));
return 0;
}
#include <cstdlib>
#include <cstdio>
main() {
double a=123.45;
double b=-1234.56;
char ptr[50];
gcvt(a,5,ptr);
printf("a value=%s\n",ptr);
gcvt(b,6,ptr);
printf("b value=%s\n",ptr);
}
『感悟』
希望下次,再写字符串和数组的问题少出一些问题