2016-10-20 2 views
1

나는 John Smith 2,2 3,1 2,2의 형식으로 입력하고 하나의 문자열로 "John Smith"를 저장 한 다음 그 다음 숫자를 벡터에 저장해야합니다. 문제는 문자열 부분이 긴 단어 수에 관계없이 가능하다는 것입니다.C++ getline 구분 기호를 숫자로 사용 하시겠습니까?

제 계획은 getLine을 사용하고 구분 기호를 '임의의 숫자'로 지정하는 것입니다. 이것이 가능한가? 나는 봤지만 아무것도 찾을 수 없었다. 감사. 이 같은

+0

아니, 구분 기호는 하나의 일반 문자입니다. 이것은 나쁜 생각입니다. –

+1

문자열을 읽고 첫 번째 숫자를 검색하십시오. –

+0

확인. 좋은 생각이야. 고맙습니다. 또한 내가 질문 한 방식에 문제가 있습니까? 나는 downvoted지고있는 것 같습니다. 다르게 말을해도 될까요? 내가 실수하면 미안해. –

답변

1

시도 뭔가 :

#include <string> 
#include <sstream> 
#include <vector> 
#include <cctype> 
#include <locale> 
#include <iterator> 
#include <algorithm> 
#include <functional> 

struct my_punct : std::numpunct<char> { 
protected: 
    virtual char do_decimal_point() const { return ','; } 
    virtual std::string do_grouping() const { return "\000"; } // groups of 0 (disable) 
}; 

struct sName { 
    std::string value; 
}; 

static inline void rtrim(std::string &s) { 
    s.erase(
     std::find_if(
      s.rbegin(), s.rend(), 
      std::not1(std::ptr_fun<int, int>(std::isspace)) 
     ).base(), 
     s.end() 
    ); 
} 

std::istream& operator>>(std::istream &in, sName &out) 
{ 
    char ch, last = 0; 
    std::ostringstream oss; 

    std::istream::sentry s(in); 
    if (s) 
    { 
     out.value.erase(); 

     do 
     { 
      ch = in.peek(); 
      if (!in) break; 
      if (std::isspace(last) && std::isdigit(ch)) break; 
      ch = in.get(); 
      oss << ch; 
      last = ch; 
     } 
     while (true); 

     out.value = oss.str(); 
     rtrim(out.value); 
    } 

    return in; 
} 

std::string input = ...; // "John Smith 2,2 3,1 2,2" 

sName name; 
std::vector<double> v; 

std::istringstream iss(input); 
iss >> name; 
iss.imbue(std::locale(iss.getloc(), new my_punct)); 
std::copy(
    std::istream_iterator<double>(iss), 
    std::istream_iterator<double>(), 
    std::back_inserter(v) 
); 
관련 문제