c++ - read string into array -
i want read string integers , whitespaces array. example have string looks 1 2 3 4 5, , want convert integer array arr[5]={1, 2, 3, 4, 5}. how should that?
i tried delete whitespaces, assign whole 12345 every array element. if don't element assigned 1.
for (int = 0; < str.length(); i++){ if (str[i] == ' ') str.erase(i, 1); } (int j = 0; j < size; j++){ // size given arr[j] = atoi(str.c_str()); }
a couple of notes:
- use
std::vector
. never know size of input @ compile time. if do, usestd::array
. - if have c++11 available you, maybe think
stoi
orstol
, throw upon failed conversion - you accomplish task
std::stringstream
allow treatstd::string
std::istream
std::cin
. recommend way - alternatively, go hard route , attempt tokenize
std::string
based on' '
delimiter, appears trying do. - finally, why reinvent wheel if go tokenization route? use boost's split function.
stringstream approach
std::vector<int> readinputfromstream(const std::string& _input, int _num_vals) { std::vector<int> toreturn; toreturn.reserve(_num_vals); std::istringstream fin(_input); for(int i=0, nextint=0; < _num_vals && fin >> nextint; ++i) { toreturn.emplace_back(nextint); } // assert (toreturn.size() == _num_vals, "error, stream did not contain enough input") return toreturn; }
tokenization approach
std::vector<int> readinputfromtokenizedstring(const std::string& _input, int _num_vals) { std::vector<int> toreturn; toreturn.reserve(_num_vals); char tok = ' '; // whitespace delimiter size_t beg = 0; size_t end = 0; for(beg = _input.find_first_not_of(tok, end); toreturn.size() < static_cast<size_t>(_num_vals) && beg != std::string::npos; beg = _input.find_first_not_of(tok, end)) { end = beg+1; while(_input[end] == tok && end < _input.size()) ++end; toreturn.push_back(std::stoi(_input.substr(beg, end-beg))); } // assert (toreturn.size() == _num_vals, "error, string did not contain enough input") return toreturn; }
Comments
Post a Comment