相关王者
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;
}