0

I have a vector that consists of an array of data after reading in a config file. Now, I will like to extract some values in the vector and passing it as int. I am able to get the value range but I am not sure how to continue from there on.

Example:

string MapXInput, MapYInput; vector <string> placeholder; cout << placeholder[0] << endl; // will cout MapXInput=12-20 cout << placeholder[1] << endl; // will cout MapYInput=13-19 MapXInput = placeholder[0].substr(10, 99); // will extract 12-20 MapYInput = placeholder[1].substr(10, 99); // will extract 13-19 int x_start, x_end; int y_start, y_end; ... // from here on, unsure how to proceed // x_start is suppose to obtain '12' and turn it into int // x_end is suppose to obtain '20' and turn it into int // y_start is suppose to obtain '13' and turn it into int // y_end is suppose to obtain '19' and turn it into int 

Note that MapXInput= and MapYInput= will always be fixed in the config file. The range value is changeable depending on the user input. I tried this:

int x_start = stoi(MapXInput[1]); 

But it produce the error

no matching function for call to 'stoi(char&)' 

End result suppose to be:

x_start = 12 x_end = 20 y_start = 13 y_end = 19 

What is the approach?

2 Answers 2

2

An easy approach is to use a std::istringstream:

std::istringstream iss{MapXInput}; // e.g. "12-20" char c; if (!(iss >> x_start >> c >> x_end && c == '-')) { std::cerr << "unable to parse MapXInput\n"; exit(EXIT_FAILURE); } 

You can think of iss >> x_start >> c >> x_end as meaning "can I parse/extract 3 values of values of whatever types x_starts, c and x_end are. && is the logical AND operator in C++. c == '-' checks the character between the ints was a hyphen. ! is the logical NOT operator, and therefore the if conditions handles cases where parsing fails or the separator is not '-'. You could other conditions in there, such as range checks on the integer values.

Sign up to request clarification or add additional context in comments.

3 Comments

Cool, it worked. Just went to read up on istringstream and didn't know this exist (I am new to C++). By the way, when I check the datatype for my x_start, it output the typeid of 'i'. I suppose this is an integer datatype?
@user3118602 -- Apart from iss and c, Tony Delroy used the variables that you declared them in your post.
Got it, just want to make sure it is an integer datatype! Thanks!
0

Splitting a string by a character. this should do the trick:

std::stringstream test("this_is_a_test_string"); std::string segment; std::vector<std::string> seglist; while(std::getline(test, segment, '_')) { seglist.push_back(segment); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.