简体   繁体   中英

C++/C: Convert a string to initializer list

I'm reading into a string s = {1,2,3} something that looks like an initializer list from a text file.

How can I do an assignment like int a[3]={1,2,3} without hardcoding it, using something like int a[3]=s; ?

As it's been said in the comments, the only way to do something like this in C++ is to manually write a parser. An example using std::vector (that you should use specially because of the lenght variability) could be the following:

#include <algorithm>
#include <vector>
#include <string>
#include <sstream>

std::vector<int> parse(const std::string& str){
  if(str.front() != '{' || str.back() != '}'){
    throw std::invalid_argument("vectors must be enclosed between braces");
  }
  std::vector<int> result;
  result.reserve(std::count(str.begin(), str.end(),',')+1); // this pays off for really big vectors
  std::stringstream stream(str.substr(1,str.size()-2));
  std::string element;
  while(getline(stream,element,',')){
    result.push_back(std::stoi(element));
  }
  return result;
}

If performance is not that important, this should do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM