2016-08-22 2 views
4

의 문자열을 선언 우리는C에서 고정 된 크기

char buffer[100]; 

는 고정 된 크기 std::string를 선언하는 방법이 있나요합니까?

+4

고정 크기 문자열로 어떤 문제를 해결하고 싶습니까? –

+0

C에서 똑같은 일을 할 수있는 옵션이 있습니다. Youncould so array . 또는 문자열에 100 자 이상을 넣을 수 없습니다. 니가하려는 일에 달렸어. –

+0

http://stackoverflow.com/questions/1571901/c-fixed-length-string-class – Shahid

답변

0

뭘하고 싶은지 모르겠지만 std::array<char, 100> buffer;을 써야합니다.

당신은 다음과 같은 문자열을 얻을 수 있습니다 :

std::string str(std::begin(buffer),std::end(buffer); 
2

당신이

std::string s; 
    s.reserve(100); 

같은 string::reserve 방법을 사용할 수 있습니다하지만 당신은 더 많은 문자를 추가 할 수 있기 때문에 이것은 크기가 고정되어 있지 예를 들어 string :: push_back이있는 문자열.

3

C++ 17에는 과 동일한 (변경 불가능한) 인터페이스를 제공하는 std::string_view이 있습니다. 한편

, 당신은 문자 배열을 포장하고 예를 들어, 선택 그것에 어떤 서비스를 추가 할 수 있습니다

template<std::size_t N> 
struct immutable_string 
{ 
    using ref = const char (&)[N+1]; 
    constexpr immutable_string(ref s) 
    : s(s) 
    {} 

    constexpr auto begin() const { return (const char*)s; } 
    constexpr auto end() const { return begin() + size(); } 
    constexpr std::size_t size() const { return N; } 
    constexpr ref c_str() const { return s; } 
    ref s; 

    friend std::ostream& operator<<(std::ostream& os, immutable_string s) 
    { 
     return os.write(s.c_str(), s.size()); 
    } 
}; 

template<std::size_t NL, std::size_t NR> 
std::string operator+(immutable_string<NL> l, immutable_string<NR> r) 
{ 
    std::string result; 
    result.reserve(l.size() + r.size()); 
    result.assign(l.begin(), l.end()); 
    result.insert(result.end(), r.begin(), r.end()); 
    return result; 
} 

template<std::size_t N> 
auto make_immutable_string(const char (&s) [N]) 
{ 
    return immutable_string<N-1>(s); 
} 

int main() 
{ 
    auto x = make_immutable_string("hello, world"); 
    std::cout << x << std::endl; 

    auto a = make_immutable_string("foo"); 
    auto b = make_immutable_string("bar"); 
    auto c = a + b; 
    std::cout << c << std::endl; 
} 
0

당신은 C에서와 정확히 일을의 C++ 방법입니다 std::array을 사용할 수 있습니다 .

std::array<char, 100> buffer; 

당신이 스택 오버 플로우에 대해 걱정하는 경우

때문에 큰 버퍼 크기 (같은, 예를 들어, 그 100 독립에 1'000'000위한 경우) 동적 대신을 할당 할 수 있습니다합니다. 사용자 인터페이스 이후

std::unique_ptr<std::array<char, 100>> buffer = std::make_unique<std::array<char, 100>>(); 

는 피연산자로 char * 소요되며,이 객체는 런타임에 크기를 쿼리 할 수 ​​있습니다,이 충분해야한다.