2010-12-16 50 views
0

我看到過類似的問題,但答案在我的Visual C++ 6上無法正常工作。 我有一個CString(visual C++ String class)數字除以逗號:如何將字符串中的所有數字逐個讀入數組(C++)

CString szOSEIDs = "5,2,6,345,64,643,25,645"; 

我希望他們一個一個地放入int數組中。 我試過stringstream,但它只給我第一個int。 有人可以幫忙嗎?

P.S. 這是我的失敗嘗試:

std::string input; 
input = (LPCTSTR)szOSE_IDs; // convert CString to string 
std::stringstream stream(input); 
while(1) { 
    int n; 
    stream >> n; 
    if(!stream) 
    break; 
    szSQL.Format("INSERT INTO TEMP_TABELA (OSE_ID) values (%d)", n); // I create SQL from my IDs now available 
    if(!TRY_EXECUTE(szSQL)) //This just a runner of SQL 
    return false; 
} 

在這種情況下,我只得到了第一個數字(5),只有我的第一個SQL將運行。 任何想法? 謝謝

回答

1

的問題是,stream >> n當它擊中你的字符串,失敗。你不能用這種方式來標記字符串 - 而是看一下像boost這樣的庫,它提供了一個很好的標記器。

但是,如果你能保證你的字符串看起來總是這樣,你可以嘗試:

int n; 
    while (stream >> n) 
    { 
    // Work with the number here 
    stream.get(); //skip the "," 
    } 

這將節省您不必在升壓等

+0

謝謝! 看起來像現在的作品!多一點測試做,我會報告回 – Hoornet 2010-12-16 09:52:31

+0

這是一個它最容易在我的情況下工作(至少現在),所以我給它正確的位:) 米赫蘭的也是非常有趣的... – Hoornet 2010-12-16 13:38:27

0
parse(CString& s, std::vector<int>* v) 

{ 
int l = s.size();//or something like this 
int res = 0; 
for(int i = 0; i < l; ++i) 
{ 
    if(s[i] == ',') 
    { 
    v->push_back(res); 
    res = 0; 
    continue; 
    } 
    res*=10; 
    res+=s[i] - '0'; 
} 
v->push_back(res); 
} 
int main() 
{ 
CString s="1,2,3,4,15,45,65,78"; 
std::vector<int> v; 
parse(s, &v); 
//... 
return 0; 
} 
+0

謝謝拉!這看起來也很有趣 – Hoornet 2010-12-16 10:23:35

+0

我注意到了你的答案,現在寫在我的助手類中作爲備份。謝謝你們! – Hoornet 2010-12-16 13:39:41

0
typedef size_t pos; 
    pos p; 
    string str("5,2,6,345,64,643,25,645"); 
    string chopped(str); 
    string strVal; 
    bool flag = 1; 
    do{ 
    p = chopped.find_first_of(","); 
    if(p == chopped.npos) 
     flag = 0; 
    strVal = chopped.substr(0,p); 
    chopped = chopped.substr(p+1); 
    //cout << chopped << endl; 
    cout << strVal << endl; 

    }while(flag); 
0
CString nums = _T("5,2,6,345,64,643,25,645"); 
CString num; 
std::vector<int> intv; 
int pos = 0; 
do { 
    if ((num = nums.Tokenize(_T(","), pos)) != _T("")) 
     intv.push_back(_ttoi(num)); 
    else 
     break; 
} while (true); 
相關問題