C++ 小技巧

相关王者

1. C++ string类如何format(格式化)字符串

方法一(推荐)

#include <sstream>
std::ostringstream buffer;
buffer<<"cplusplus.me"<<"_"<<2016<<"_"<<1;
string str = buffer.str()

方法二(不推荐)

char buffer[BUFFER_SIZE];
sprintf(buffer,"%s_%d_%d","cplusplus.me",2016,1);
string str = buffer;

2. C++ How to write a string vector to file

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

// write vector v to text.txt
void write(vector<string> v){
	ofstream file;
	file.open("text.txt");
	for(int i=0;i<v.size();++i){
		file<<v[i]<<endl;
	}
	file.close();
}

// read data from from text.txt and store it in vector v
void read(vector<string> &v){
	ifstream file;
	file.open("text.txt");
	string line;
	while(getline(file, line)){
		v.push_back(line);
	}
	file.close();
}

int main()
{
	vector<string> v  = {"My", "name", "is", "John", "Smith"};
	cout<<"Vector: ";
	for(int i=0;i<v.size();++i)
		cout<<v[i]<<" ";
	cout<<endl;
	
	//  writing v to file "text.txt"
	write(v);
	
	vector<string> temp;
	// reading vector from "text.txt" and storing data in temp
	read(temp);
	cout<<"Vector After Reading from File: ";
	for(int i=0;i<temp.size();++i)
		cout<<temp[i]<<" ";
	cout<<endl;
	
}

3. string转为int, float, double

方法一

#include <iostream>
#include <windows.h>
#include <string>
int main()
{
    std::string getdata = "1234";
    int n_Val = std::stoi(getdata);
    int l_Val = std::stoi(getdata);
    std::cout << n_Val << std::endl;
    std::cout << l_Val << std::endl;
    
    std::string getdata = "1234.000";
    int d_Val = std::stof(getdata);
    std::cout << d_Val << std::endl;
    
    system("pause");  
    return 0;
}

方法二

#include <iostream>  
#include <sstream>    //使用stringstream需要引入这个头文件  
using namespace std;  

int main()
{
    int a;
    float b;
    string a_str = "123";
    string b_str = "333.2";

	istringstream isa_str(a_str);
	isa_str >> a;
	istringstream isb_str(b_str);
	isb_str >> b;

    cout << a << " " << b << endl;
    return 0;
}

C++字符串分割方法总结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

且漫CN

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值