簡體   English   中英

如何從std :: string中獲取2個字符並將其轉換為C ++中的int?

[英]How to take 2 characters from std::string and convert it to int in C++?

在C ++中,我有一個字符串,例如std::string string = "1234567890"

我有一個定義為std::vector<int> vec的整數std::vector<int> vec

如何計算vec = stoi(string.at(1) + string.at(2))這樣它將給我可以插入此向量的整數12

據我了解,您想將前兩個字符作為字符串檢索,將其轉換為int並插入到向量中:

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

有了C ++ 11支持,您可以使用std::stoi代替字符串流。

使用字符串流:

#include <sstream>

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

最簡單的方法是提取子字符串而不是單個字符。 使用operator +進行懷抱,然后在結果字符串上調用stoi

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

上面將在源字符串中任意位置處連接字符串。 如果您真的只需要提取連續的字符,則只需調用一次substr就可以了:

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

據我正確理解,您想從字符串的前兩個字符組成一個整數。 然后可以通過以下方式完成

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

通用方法如下

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;

您所需要做的就是為字符串指定所需的迭代器范圍。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM