If the user enters an integer, for example 4210, how can I put every number of this integer into a vector in C ++?
This can be done like this:
std::vector<int> numbers; int x; std::cin >> x; while(x>0) { numbers.push_back(x%10); x/=10; } std::reverse(numbers.begin(), numbers.end());
Or, if you prefer to use std::string, you can use:
std::string
std::vector<int> intVector; int x; std::cin >> x; for (const auto digit : std::to_string(x)) { intVector.push_back(digit - '0'); }
This assumes your compiler can use C ++ 11.
Living example
, int, , , ... , .
int
"4321" std::vector<int>{4, 3, 2, 1}, :
"4321"
std::vector<int>{4, 3, 2, 1}
std::string input; std::cin >> input; std::vector<int> vec; for (char const c: input) { assert(c >= '0' and c <= '9' and "Non-digit character!"); vec.push_back(c - '0'); }
Source: https://habr.com/ru/post/1534696/More articles:How to remove all activity in a stack when you press the return button - androidSQL query to get the distribution of field values - sqlEfficient free / open source SOCP (second-order cone programming) solvers - convex-optimizationCheck constraints in cvxpy with valid values - optimizationGoogle Plus single-board single-user mode: onConnected is never called in a new installation - androidИзменение цвета звезд и отображение половины звездного рейтинга с помощью AngularUI Star Rating - angularjsPython regex validation using py.test - pythonSed - Replace the nearest next line / word following a specific pattern - unixClang дает очень разную производительность для выражений, которые интуитивно должны быть эквивалентными - c++Unable to change site visibility in Wordpress - search-engineAll Articles