c++ string to vector int

To convert a string to a vector of integers in C++, you can follow these steps:

  1. Include the necessary header files: cpp #include <iostream> #include <string> #include <vector>

  2. Declare a string variable to store the input string: cpp std::string inputString;

  3. Get the input string from the user: cpp std::cout << "Enter a string: "; std::getline(std::cin, inputString);

  4. Declare a vector to store the converted integers: cpp std::vector<int> numbers;

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

  6. 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.