2010-11-23 138 views
2

我正在尋找一種方法來將具有指定分隔符(如斜槓或空格)的字符串轉換爲分隔符分隔的整數數組。解析字符串到整數數組

例如,如果用戶輸入12/3/875/256,我需要檢索數組{12, 3, 875, 256}。理想情況下,它可以處理任意長度。

我試着逐字掃描字符串,並將所有不是分隔符的東西存儲在一個臨時變量中,下次遇到分隔符字符時將它添加到數組中。不幸的是,類型轉換是一個令人頭疼的問題。有沒有更簡單的方法來做到這一點?

回答

2

您可以設置「/」來分隔符,並使用函數getline讀?那麼你必須將每個變量放到一個變量中,並且你需要知道這個變量的大小 - 也許你可以通過數組並計算斜線?那麼你會知道這一點,並可以先設置陣列。您可能需要將每個字符串段解析爲一個int,這可能也可能不困難。 (有一段時間沒有使用C++,我不記得一個方便的方法。)

請參閱here瞭解如何完成這個小示例(3篇文章)。

1

看看this other answer。它甚至有一個使用boost :: tokenizer的標記器代碼的例子。

編輯:

我複製與neccessary修改有代碼:

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

using namespace std; 
using namespace boost; 

int main(int argc, char** argv) 
{ 
    string text = "125/55/66"; 
    vector<int> vi; 

    char_separator<char> sep("/"); 
    tokenizer<char_separator<char> > tokens(text, sep); 
    BOOST_FOREACH(string t, tokens) 
    { 
     vi.push_back(lexical_cast<int>(t)); 
    } 

    copy(vi.begin(), vi.end(), ostream_iterator<int>(cout, "\n")); 
} 

會打印:

125 
55 
66 
0

你可以使用的Boost.splitBoost.lexical_cast相結合,打破了用你想要的任何分隔符串起來,然後你就可以用詞彙把它們全部投射出去。

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


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

int main() 
{ 
    std::string s = "11/23/2010"; 
    std::vector<std::string> svec; 
    std::vector<int> ivec; 

    // split the string 's' on '/' delimiter, and the resulting tokens 
    // will be in svec. 
    boost::split(svec, s, boost::is_any_of("/")); 

    // Simple conversion - iterate through the token vector svec 
    // and attempt a lexical cast on each string to int 
    BOOST_FOREACH(std::string item, svec) 
    { 
     try 
     { 
      int i = boost::lexical_cast<int>(item); 
      ivec.push_back(i); 
     } 
     catch (boost::bad_lexical_cast &ex) 
     { 
      std::cout << ex.what(); 
     } 
    } 

    return 0; 
} 

未經測試......在這臺機器上沒有提升。

,你可以用它來轉換std::string/char *int類型的其他方式直接涉及stringstream使用,或C結構,如atoi