how to extract specific integers in a mixed string-integer line in c++ -
i reading text file in c++, example of lines in it:
remove 1 2 cost 13.4
how disregard things except 2 integers after remove, "1" , "2" , put them in 2 integer variable?
my incomplete code:
ifstream file("input.txt"); string line; int a, b; if(file.is_open()) { while (!file.eof()) { getline (file, line); istringstream iss(line); if (line.find("remove") != string::npos) { iss >> >> b; // not work, not sure how // write code here } } }
here few options:
use
stringstream
created line findremove
token , parse next 2 integers. in other words, replace this:if (line.find("remove") != string::npos) { iss >> >> b; // not work, not sure how // write code here }
with this:
string token; iss >> token; if (token == "remove") { iss >> >> b; }
create
stringstream
rest of line (6
length of "remove" token).string::size_type pos = line.find("remove"); if (pos != string::npos) { istringstream iss(line.substr(pos + 6)); iss >> >> b; }
call
seekg
method on linestringstream
set input position indicator of stream after "remove" token.string::size_type pos = line.find("remove"); if (pos != string::npos) { iss.seekg(pos + 6); iss >> >> b; }
Comments
Post a Comment