In C++, I have a string, such that std::string string = "1234567890".

and I have a vector of integers defined as std::vector<int> vec

How can I compute vec = stoi(string.at(1) + string.at(2)) so it will give me the integer 12 that I can insert to this vector?

有帮助吗?

解决方案 3

The easiest way is by extracting substrings rather than individual characters. Use operator + to concetanate them, and call stoi on the resulting string:

vec.push_back(stoi(string.substr(0, 1) + string.substr(1, 1)));
// vec now ends with 12

The above will concatenate strings at arbitrary locations in the source string. If you really need only extract consecutive characters, a single call to substr will suffice:

vec.push_back(stoi(string.substr(0, 2)));

其他提示

From what I understand, you want to retrieve the first 2 characters as a string, convert it to int and insert to the vector:

std::vector<int> vec;
std::string str = "1234567890";

// retrieve the number:
int i;
std::istringstream(str.substr(0,2)) >> i;

// insert it to the vector:
vec.push_back(i);

With C++11 support, you might use std::stoi instead of string stream.

Use a stringstream:

#include <sstream>

std::stringstream ss(string.substr(0,2));
int number;
ss >> number;

As I have correctly understood you you want to form an integer number from the first two characters of the string. Then it can be done the following way

std::vector<int> vec = { ( ( s.length() >= 1 && is_digit( s[0] ) ) ? s[0] - '0' : 0 ) * 10 +
                         ( ( s.length() > 1 && is_digit( s[1] ) ) ? s[1] - '0' : 0 ) };

The general approach is the following

std::string s = "123456789";
std::vector<int> v( 1, std::accumulate( s.begin(), s.end(), 0,
    []( int acc, char c ) { return ( isdigit( c ) ? 10 * acc + c - '0' : acc ); } ) );

std::cout << v[0] << std::endl;

All you need is to specify the required range of iterators for the string.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top