2011-12-23 70 views
-3

這是我之前的問題的後續。將字符數組分割成字符串

Parsing file names from a character array

答案是相關的,但我仍然有麻煩。當字符串被拆分時,我似乎無法讓它們正確地輸出到我的錯誤日誌中,不管是字符串還是cstring,說實話,我不完全理解他的答案是如何工作的。那麼,是否有人對紳士提供的答案有了進一步的解釋。我如何將字符數組分成更多的字符串,而不是全部寫出來。這是答案。

std::istringstream iss(the_array); 
std::string f1, f2, f3, f4; 
iss >> f1 >> f2 >> f3 >> f4; 

想象一下,我有30個不同的字符串。當然,我不能寫f1,f2 .... f30。

有關如何做到這一點的任何建議?

+6

如果您需要說明,請對答案進行評論。 –

+2

也請停止簽署帖子 –

+0

@ TomalakGeret'kal簽名帖? –

回答

3

你甚至可以避免明確的循環,並嘗試一種現代C++更自然的方式,如果你願意的話。

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

int main() 
{ 
    // Your files are here, separated by 3 spaces for example. 
    std::string s("picture1.bmp file2.txt random.wtf dance.png"); 

    // The stringstream will do the dirty work and deal with the spaces. 
    std::istringstream iss(s); 

    // Your filenames will be put into this vector. 
    std::vector<std::string> v; 

    // Copy every filename to a vector. 
    std::copy(std::istream_iterator<std::string>(iss), 
    std::istream_iterator<std::string>(), 
    std::back_inserter(v)); 

    // They are now in the vector, print them or do whatever you want with them! 
    for(int i = 0; i < v.size(); ++i) 
    std::cout << v[i] << "\n"; 
} 

這是處理像「我有30個不同的字符串」的場景的明顯方式。將它們存儲在任何地方,std :: vector可能是合適的,這取決於你可能想要對文件名進行什麼操作。這樣你就不需要給每個字符串一個名字(f1,f2,...),例如,如果需要的話,你可以通過向量的索引來引用它們。

+0

+1這比我的建議好。 – hmjd