C++ Extract int from string using stringstream -
i trying write short line gets string using getline , checks int using stringstream. having trouble how check if part of string being checked int. i've looked how this, seem throw exceptions - need keep going until hits int.
later adjust account string doesn't contain ints, ideas on how past part?
(for now, i'm inputting test string rather use getline each time.)
int main() { std::stringstream ss; std::string input = "a b c 4 e"; ss.str(""); ss.clear(); ss << input; int found; std::string temp = ""; while(!ss.eof()) { ss >> temp; // if temp not int ss >> temp; // keep iterating } else { found = std::stoi(temp); // convert int } } std::cout << found << std::endl; return 0; }
you make of validity of stringstream int conversion:
int main() { std::stringstream ss; std::string input = "a b c 4 e"; ss << input; int found; std::string temp; while(std::getline(ss, temp,' ')) { if(std::stringstream(temp)>>found) { std::cout<<found<<std::endl; } } return 0; }
Comments
Post a Comment