2012-02-14 16 views

答えて

3

できません。デフォルトの区切り文字は\n次のとおりです。他の区切り文字については

while (std::getline (std::cin, str) // '\n' is implicit 

、それらを渡す:

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

をただし、区切り文字はchar型のものであり、このように一つだけ「分割文字」を使用することができますが、ありません一致しないもの

入力が既にstd::stringのようなコンテナ内にある場合は、find_first_not_ofまたはfind_last_not_ofを使用できます。


他の質問では、すべての回答を検討してもよろしいですか? 1つはistream::operator>>(std::istream&, <string>)を使用します。これは一連の空白以外の文字と一致します。

3

あなたはしません。 getlineは簡単な仕事のための簡単なツールです。より複雑なものが必要な場合は、RegExなどのより複雑なツールを使用する必要があります。

0

あなたはstd::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; 
} 
関連する問題