2012-02-14 2 views

답변

3

수 없습니다. 기본 구분 기호 \n입니다 : 그러므로 당신은 단지 하나의 "분할 문자"를 사용할 수 있습니다, 그러나

while (std::getline (std::cin, str, ' ') // splits at a single whitespace 

은 구분 기호는 char 형이다,하지만 :

다른 구분 기호를 들어
while (std::getline (std::cin, str) // '\n' is implicit 

,이를 통과 일치하지 않는 것.

입력 내용이 이미 std::string과 같은 컨테이너 내부에있는 경우 find_first_not_of 또는 find_last_not_of을 사용할 수 있습니다.


다른 질문으로 모든 대답을 고려 했습니까? 하나는 istream::operator>>(std::istream&, <string>)을 사용하며 공백이 아닌 문자 시퀀스와 일치합니다.

3

그렇지 않습니다. getline은 간단한 작업을위한 간단한 도구입니다. 좀 더 복잡한 것이 필요하다면 RegEx와 같은 좀 더 복잡한 도구를 사용해야합니다.

0

std::getline()을 사용하여 원하는 것을 할 수는 없지만 직접 만들 수는 있습니다. 여기에 getline 변종이 있는데, 문자가 구분 기호인지 여부를 나타내는 술어 (함수, 펑터, 람다 (C++ 11 일 경우))를 지정하고 몇 가지 오버로드 문자를 사용하여 구분 기호 문자 (예 : strtok()) :

#include <functional> 
#include <iostream> 
#include <string> 

using namespace std; 

template <typename Predicate> 
istream& getline_until(istream& is, string& str, Predicate pred) 
{ 
    bool changed = false; 
    istream::sentry k(is,true); 

    if (bool(k)) { 
     streambuf& rdbuf(*is.rdbuf()); 
     str.erase(); 

     istream::traits_type::int_type ch = rdbuf.sgetc(); // get next char, but don't move stream position 
     for (;;ch = rdbuf.sgetc()) { 
      if (istream::traits_type::eof() == ch) { 
       is.setstate(ios_base::eofbit); 
       break; 
      } 
      changed = true; 
      rdbuf.sbumpc(); // move stream position to consume char 
      if (pred(istream::traits_type::to_char_type(ch))) { 
       break; 
      } 
      str.append(1,istream::traits_type::to_char_type(ch)); 
      if (str.size() == str.max_size()) { 
       is.setstate(ios_base::failbit); 
       break; 
      } 
     } 

     if (!changed) { 
      is.setstate(ios_base::failbit); 
     } 
    }    

    return is; 
} 

// a couple of overloads (along with a predicate) that allow you 
// to pass in a string that contains a set of delimiter characters 

struct in_delim_set : unary_function<char,bool> 
{ 
    in_delim_set(char const* delim_set) : delims(delim_set) {}; 
    in_delim_set(string const& delim_set) : delims(delim_set) {}; 

    bool operator()(char ch) { 
     return (delims.find(ch) != string::npos); 
    }; 
private: 
    string delims; 

}; 

istream& getline_until(istream& is, string& str, char const* delim_set) 
{ 
    return getline_until(is, str, in_delim_set(delim_set)); 
} 

istream& getline_until(istream& is, string& str, string const& delim_set) 
{ 
    return getline_until(is, str, in_delim_set(delim_set)); 
} 

// a simple example predicate functor 
struct is_digit : unary_function<char,bool> 
{ 
    public: 
     bool operator()(char c) const { 
      return ('0' <= c) && (c <= '9'); 
     } 
}; 


int main(int argc, char* argv[]) { 
    string test; 

    // treat anything that's not a digit as end-of-line 
    while (getline_until(cin, test, not1(is_digit()))) { 
     cout << test << endl; 
    } 

    return 0; 
} 
관련 문제