parsing - extracting digits from input string c++ -
i'm trying parsing input string reactions read file @ formula :2w+b=8a+10z, i'm not interested in characters need split , extract integer values put them in vector i.e vector associated reaction here :[2 1 8 10] thought many things: std::strtok(),isdigital(),find_first_of()
didn't work integer values ... can body ??
here try:
int main() { std::string input; std::getline(std::cin, input); std::stringstream stream(input); while(1) { int n; stream >> n; char * pch; pch = strtok (input," "); while (pch != null) { printf ("%s\n",pch); pch = strtok (null, " ,."); } } }
you this, comments see code
#include <iostream> #include <string> #include <vector> std::vector<int> split(std::string str) { std::vector<int> result; // contain different ints // set pointer first character in string char const* pch = str.c_str(); std::string digit; // buffer keep digits if more 1 int sign = 1; // each number has sign -1 or 1 (; *pch; ++pch) { if (std::isdigit(*pch)) // if digit, put in temp buffer { digit += *pch; } else if (std::isalpha(*pch)) // if not digit evaluate ones have { if (digit.empty()) // none assume 1 before letter e.g. w+2b { result.push_back(1*sign); } else { result.push_back(stoi(digit)*sign); digit = ""; } } else // determine sign of number { digit = ""; if (*pch == '+') { sign = 1; } else if (*pch == '-') { sign = -1; } } } return result; } int main() { using namespace std; string expr{"-2w+b=-8a+10z"}; auto digits = split(expr); (auto& digit : digits) { cout << digit << endl; } return 0; }
Comments
Post a Comment