如何在C ++中将字符串向量转换为整数向量? [英] How do I convert vector of strings into vector of integers in C++?

查看:75
本文介绍了如何在C ++中将字符串向量转换为整数向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串向量.需要帮助弄清楚如何将其转换为整数向量,以便能够对其进行算术运算.谢谢!

I have a vector of strings. Need help figuring out how to convert it into vector of integers in order to be able to work with it arithmetically. Thanks!

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main(int argc, char* argv[]) {

    vector<string> vectorOfStrings;
    vectorOfStrings.push_back("1");
    vectorOfStrings.push_back("2");
    vectorOfStrings.push_back("3");

    for (int i=0; i<vectorOfStrings.size(); i++)
    {
        cout<<vectorOfStrings.at(i)<<endl;
    }

    vector<int> vectorOfIntegers;

    //HELP NEEDED HERE
    //CONVERSION CODE from vector<string> to vector<int> 

    int sum;
    for (int i=0; i<vectorOfIntegers.size(); i++)
    {
        sum += vectorOfIntegers.at(i);
    }
    cout<<sum<<endl;
    cin.get();

    return 0;
}

推荐答案

有多种将字符串转换为int的方法.

There are mulitple ways of converting a string to an int.

解决方案1:使用旧版C功能

Solution 1: Using Legacy C functionality

int main()
{
    //char hello[5];     
    //hello = "12345";   --->This wont compile

    char hello[] = "12345";

    Printf("My number is: %d", atoi(hello)); 

    return 0;
}

解决方案2:使用 lexical_cast (最合适和最简单)

Solution 2: Using lexical_cast(Most Appropriate & simplest)

int x = boost::lexical_cast<int>("12345"); 

try-catch 包围以捕获异常.

解决方案3:使用 C ++流

std::string hello("123"); 
std::stringstream str(hello); 
int x;  
str >> x;  
if (!str) 
{      
   // The conversion failed.      
} 

这篇关于如何在C ++中将字符串向量转换为整数向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆