2011-08-21 80 views
2

我有一個字符串的矢量。需要幫助瞭解如何將其轉換爲整數向量,以便能夠用算術方式處理它。謝謝!如何將字符串向量轉換爲C++中的整數向量?

#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; 
} 

回答

10

有轉換的多張的方式一個字符串到一個int。

解決方案1:使用傳統C功能

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(最適當&簡單)

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

環繞通過try-catch捕捉異常。

解決方案3:使用C++ Streams

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

即使您檢查了「if(!str)':http://ideone.com/YjNY2,std :: stringstream也可能失敗。那就是'else'仍然失敗! – Nawaz

+0

@Nawaz:那不是失敗;流中只剩下一些數據。 –

+0

如果必須轉換_entire_輸入以確保轉換成功,請檢查'str.str()。empty()'(和'str'對於'stringstream'對象來說是一個非常糟糕的名字!) –

5

使用boost::lexical_cast。並用try-catch塊包圍它。

try 
{ 
    for (size_t i=0; i<vectorOfStrings.size(); i++) 
    { 
     vectorOfIntegers.push_back(boost::lexical_cast<int>(vectorOfStrings[i])); 
    } 
} 
catch(const boost::bad_lexical_cast &) 
{ 
    //not an integer 
} 

或者你可以使用Boost.Spirit解析器(其中someone claims is faster甚至比atoi())爲:使用你的代碼

int get_int(const std::string & s) 
{ 
    int value = 0; 
    std::string::const_iterator first = s.begin(); 
    bool r = phrase_parse(first,s.end(),*int_[ref(value)=_1], space); 
    if (!r || first != s.end()) throw "error"; 
    return value; 
} 

//Usage 
int value = get_int("17823"); 
std::cout << value << std::endl; //prints 17823 

完整的演示:http://ideone.com/DddL7

+0

我敢肯定,OP假定小數,但對我來說,lexical_cast的<>缺乏的十六進制支持限制了其有效性。 – srking

+0

@srking:你的意思是'lexical_cast'缺少十六進制的支持嗎? – Nawaz

+0

看到這個例子: http://stackoverflow.com/questions/1070497/c-convert-hex-string-to-signed-integer 的確,lexical_cast (「0x10」)咳嗽一個毛球。 – srking

0

有兩個獨立的任務。

  1. 轉換一個字符串爲整數
  2. 擁有的東西,可以從A轉換爲B,轉換std::vector<A>std::vector<B>

我建議你儘量分開做出來,然後合併結果。如果其中一項任務證明有困難,您將能夠提出更有針對性的問題。

2
#include <string> 
#include <vector> 

#include <iterator> 
#include <algorithm> 
#include <boost/lexical_cast.hpp> 

using namespace std; 

int stringToInteger(const std::string& s) 
{ 
    return boost::lexical_cast<int>(s); 
} 

int main(int /*argc*/, char* /*argv*/[]) 
{ 
    vector<string> vectorOfStrings; 

    // .. 

    vector<int> vectorOfIntegers; 
    std::transform(vectorOfStrings.begin(), vectorOfStrings.end(), std::back_inserter(vectorOfIntegers), stringToInteger); 

    // .. 
} 

您可以用您的首選轉換函數替換stringToInteger(..)的實現。

1

這是使用上述評論組成的工作版本。

#include <iostream> 
#include <string> 
#include <vector> 
#include <sstream> 

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; 
    int x; 
    for (int i=0; i<vectorOfStrings.size(); i++) 
    { 
     stringstream str(vectorOfStrings.at(i)); 
     str >> x; 
     vectorOfIntegers.push_back(x); 
    } 

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

    return 0; 
} 
0

將字符串轉換爲整數的最常用方法是使用stringstream和函數模板。如果您使用的是十六進制,則可以選擇設置轉換基礎。 boost庫在你的例子中也會有所幫助。

#include <iostream> 
#include <string> 
#include <vector> 

#include <sstream> 
#include <stdexcept> 
#include <boost/static_assert.hpp> 
#include <boost/foreach.hpp> 

/****************************************************************************** 
* Handy string to type conversion 
* First parameter is the string to convert 
* Second optional parameter is the number base, e.g. std::hex 
* 
* Because this is a function template, the compiler will instantiate one 
* instance of the function per type 
*****************************************************************************/ 
// the std::dec thingy is actually a function, so extra glue required. 
typedef std::ios_base& (*ios_base_fn)(std::ios_base& str); 
template <class T> 
T strtotype(const std::string& s, ios_base_fn base = std::dec) 
{ 
    // C++ can't convert 8-bit values, they are *always* treated 
    // as characters. :( At least warn the user. 
    // this gives a cryptic error message, but better than nothing. 
    BOOST_STATIC_ASSERT(sizeof(T) > 1); 

    T val; 
    std::istringstream iss(s); 
    iss >> base >> val; 
    if(iss.fail()) 
     throw std::runtime_error("Error: strtotype(): Can't convert string '" + s + "' to numeric value"); 
    return val; 
} 

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; 

    for(size_t i = 0; i < vectorOfStrings.size(); i++) 
     vectorOfIntegers.push_back(strtotype<int>(vectorOfStrings[i])); 

    // or better yet, use boost_foreach 
    BOOST_FOREACH(const string& s, vectorOfStrings) 
     vectorOfIntegers.push_back(strtotype<int>(s)); 

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

    return 0; 
} 

如果您不想或不能使用boost,您可以刪除strtotype中的sizeof()檢查。但是,請千萬小心,不要嘗試將字符串轉換爲單個字節。這樣做只會轉換字節的第一個半字節而失敗。

如果你起訴GNU工具,然後編譯如下所示:

g++ -Wall -O3 -I /path/to/boost/include main.cpp 

,或者如果您刪除相關提振位:

g++ -Wall -O3 main.cpp 
0

什麼:

#include <algorithm> 
#include <boost/lexical_cast.hpp> 

template<typename C1, typename C2> 
void castContainer(const C1& source, C2& destination) 
{ 
    typedef typename C1::value_type source_type; 
    typedef typename C2::value_type destination_type; 
    destination.resize(source.size()); 
    std::transform(source.begin(), source.end(), destination.begin(), boost::lexical_cast<destination_type, source_type>); 
} 

它可以將矢量< string>轉換爲矢量< int>,也可以將其他容器< T1>進入容器2 < T2>,例如:列表 - >列表。

全碼:

#include <iostream> 
#include <vector> 
#include <algorithm> 
#include <iterator> 
#include <string> 
#include <boost/lexical_cast.hpp> 

template<typename C1, typename C2> 
void castContainer(const C1& source, C2& destination) 
{ 
    typedef typename C1::value_type source_type; 
    typedef typename C2::value_type destination_type; 
    destination.resize(source.size()); 
    std::transform(source.begin(), source.end(), destination.begin(), boost::lexical_cast<destination_type, source_type>); 
} 

template<typename T, typename T2> 
std::vector<T>& operator<<(std::vector<T>& v, T2 t) 
{ 
    v.push_back(T(t)); 
    return v; 
} 

main(int argc, char *argv[]) 
{ 
    std::vector<std::string> v1; 
    v1 << "11" << "22" << "33" << "44"; 
    std::cout << "vector<string>: "; 
    std::copy(v1.begin(), v1.end(), std::ostream_iterator<std::string>(std::cout, ", ")); 
    std::cout << std::endl; 

    std::vector<int> v2; 
    castContainer(v1, v2); 

    std::cout << "vector<int>: "; 
    std::copy(v2.begin(), v2.end(), std::ostream_iterator<int>(std::cout, ", ")); 
    std::cout << std::endl; 
} 
相關問題