C++ string与vector类型相互转换之stringstream

1.stringstream类型转换用法
streamstring在调用str()时,会返回临时的string对象。而因为是临时的对象,所以它在整个表达式结束后将会被析构。
如果需要进一步操作string对象,先把其值赋给一个string变量后再操作。
//sample
stringstream ss("012345678901234123456789");  
//错误  
const char* cstr2 = ss.str().c_str();  
//正确  
const string& str2 = ss.str();  
const char* cstr2 = str2.c_str();  
//stringstream清空缓冲区
stringstream stream(“abcdefghi”);
stream.str(“”);

2.string转vector类型
#include 
#include 
#include 
#include 
using namespace std;
//1.string类型转vector类型
void string_to_vector_float(std::vector& fea){
  string str = "-0.0647031 -0.0206785 -0.0439941 -0.0323903 -0.0139745 -0.0208939 0.0289745 0.0277657 -0.0807781 -0.0288254";
  stringstream ss(str);
  string buf;
  vector vec;
  //vector vec(1024);//可以初始化时指定vecrot容器大小
  while(ss >> buf)
    vec.push_back(atof(buf.c_str()));

  cout <<"vector容器大小: "<< vec.size() << endl;
  cout <<"vector容器容量: "<< vec.capacity() << endl;
  
  fea = vec;
}

int main()
{
  vector vec;

  string_to_vector_float(vec);
  
  //1.C++11 usage:打印结果
#if 0
  for(auto ff : vec)
    cout << ff << endl;
#endif

//2.打印结果
  for(int i = 0; i < vec.size(); i++){
    if(i < 255)
      cout  << vec[i] << " " ;
    else if(i == 255)
      cout  << vec[i] ;
  }
  cout  << endl;
  
  return 0;
}

3.vector转string类型
#include 
#include 
#include 
#include 
#include 
#include "json/json.h"
#include 
using namespace std;

int ReadFromFile(string fileName)
{
  ifstream fin;
  fin.open(fileName);
  assert(fin.is_open());

  Json::Reader reader;
  Json::Value  root;
  if(reader.parse(fin, root, false) != true)
    return -1;

  cout << "arraySize = " << root["name"].size() << endl;
  cout << "my name is:" << root["name"] << endl;
}

int WriteToFile(string fileName)
{
  ofstream fout;
  fout.open(fileName);
  assert(fout.is_open());
  Json::Value root;
  //root["array"]["array1"]["name"] = "xiaozhao";
  root["name"] = "xiaozhao";
  fout << root.toStyledString() << endl;
  fout.close();
  return 0;
}

void vec2string(vector &feature, string &f_data){
  std::stringstream ss;
  for(int i = 0; i < 15; i++){
    feature.push_back(i);
  }
  cout << "v.size() = " << feature.size() << endl;
  for(size_t i = 0; i < feature.size(); ++i)
  {
    if(i != 0)
      ss << " ";
    ss << feature[i];
  }
  
  f_data = ss.str();
  cout << "ss = " << ss.str() << endl;
  ss.str(“”);//使用同一个stringstream对象,需要使用其对象方法str来重置stringstream的buffer,这样能确保stringstream占用的内存不会越积越多。
  cout << "ss = " << ss.str() << endl;
}

int main()
{
   string str;
  //WriteToFile("test.json");
  //ReadFromFile("test.json");
  vector fea;
  vec2string(fea, str);
  cout << “str = “ << str << endl;

  return 0;
}

Json for C++库下载:
# git clone https://gitee.com/Tocy/SampleCode

你可能感兴趣的:(C++学习)