CPP文件读入/字符串处理

文件读入写出

#include<fstream>  //用这一个即可
#include<istream>
#include<ostream>
//写出
ofstream out;  
out.open("Hello.txt", ios::in|ios::out|ios::binary) ;
out.close();

//读入
ifstream in;  
in.open("Hello.txt", ios::in|ios::out|ios::binary) ; 
in.close(); 

字符串处理

数字转字符串

方法一:

//第一个参数必须是指向char的指针,,不能是string

//整数
char str[10]; 
int a=123;
sprintf(str,%d”,a);
//小数
char str[10]; 
double a=123.321;
sprintf(str,%.3lf,a);

方法二:(速度慢,不适合大型数据)

利用stringstream

#include <string>
#include <sstream>

int main(){
    double a = 123.32;
    string res;
    stringstream ss;
    ss << a;
    ss >> res;//或者 res = ss.str();
    return 0;
}

字符串转数字

方法一:

char str[]=1234321; 
int a; 
sscanf(str,%d”,&a); 
char str[]=123.321; 
double a; 
sscanf(str,%lf”,&a); 

方法二:(速度慢,不适合大型数据)

int main(){
    string a = "123.32";
    double res;
    stringstream ss;
    ss << a;
    ss >> res;
    return 0;
}

也可以使用
atoi(),atol(),atof().

参考博客:
https://www.cnblogs.com/bluestorm/p/3168719.html
https://blog.csdn.net/michaelhan3/article/details/75667066/
https://www.cnblogs.com/hdk1993/p/5853233.html

猜你喜欢

转载自blog.csdn.net/baidu_41560343/article/details/88692654