user3118602
user3118602

Reputation: 583

Extracting value from a vector in C++

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?

Upvotes: 0

Views: 1112

Answers (2)

Tony Delroy
Tony Delroy

Reputation: 106236

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.

Upvotes: 2

Darian Lopez Utra
Darian Lopez Utra

Reputation: 83

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);
}

Upvotes: 0

Related Questions