将字符串转换为整数向量

Convert string to a vector of integers

本文关键字:整数 向量 转换 字符串      更新时间:2023-10-16

我需要在C 中制作功能,该字符串仅包含数字,例如:

string s = "7654321" 

并将其转换为整数的向量。因此向量应该这样:

vec[1] = '7'
vec[2] = '6'

等。

我试图使用isstringstream,但这在这种情况下没有用,因为字符串中没有空间。

您可以使用for loop迭代字符串,并使用push_back()和-'0'

填充每个值

假设向量vec;

void fillVec(const string str1, vector<char> & vec) {
    for(int i = 0; i < str1.length(); i++)
        vec.push_back(str1[i]) - '0';
}

实施此

的示例程序
// Example program
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void fillVec(const string, vector<int> &); 
int main()
{
  vector<int> vec;
  string str1 = "1234567";
  fillVec(str1, vec);
    for(int i = 0; i < vec.size(); i++)
    cout << vec[i] << ", ";
    return 0;

}
void fillVec(const string str1, vector<int> & vec) {
        for(int i = 0; i < str1.length(); i++)
            vec.push_back(str1[i]-'0');
}