天天看點

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