c++ string to vector int
To convert a string to a vector of integers in C++, you can follow these steps:
Include the necessary header files:
cpp #include <iostream> #include <string> #include <vector>
Declare a string variable to store the input string:
cpp std::string inputString;
Get the input string from the user:
cpp std::cout << "Enter a string: "; std::getline(std::cin, inputString);
Declare a vector to store the converted integers:
cpp std::vector<int> numbers;
Extract individual integers from the string using a loop. You can use a stringstream to help with the conversion:
cpp std::stringstream ss(inputString); int number; while (ss >> number) { numbers.push_back(number); }
Print the vector of integers:
cpp std::cout << "Converted integers: "; for (int num : numbers) { std::cout << num << " "; } std::cout << std::endl;
Here is the complete code example:
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
int main() {
std::string inputString;
std::cout << "Enter a string: ";
std::getline(std::cin, inputString);
std::vector<int> numbers;
std::stringstream ss(inputString);
int number;
while (ss >> number) {
numbers.push_back(number);
}
std::cout << "Converted integers: ";
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
This code takes an input string from the user and converts it into a vector of integers. It uses a stringstream to extract individual integers from the string and stores them in the vector. Finally, it prints the vector to display the converted integers.