2011-12-23 7 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

for 루프를 명시 적으로 회피하고 심지어 현대 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

관련 문제