ProgramingTip

std :: string에 int 추가

bestdevel 2020. 11. 6. 19:01
반응형

std :: string에 int 추가


이 질문에 이미 답변이 있습니다.

이 코드가 디버그 어설 션 실패를 제공하는 이유는 무엇입니까?

   std::string query;
   int ClientID = 666;
   query = "select logged from login where id = ";
   query.append((char *)ClientID);

std::string::append()방법은 NULL이 될 인수가 종료를 기대합니다 ( char*).

생산하는 여러가 가지 방법이 있습니다 string을 containg는 int:

  • std::ostringstream

    #include <sstream>
    
    std::ostringstream s;
    s << "select logged from login where id = " << ClientID;
    std::string query(s.str());
    
  • std::to_string (C ++ 11)

    std::string query("select logged from login where id = " +
                      std::to_string(ClientID));
    
  • boost::lexical_cast

    #include <boost/lexical_cast.hpp>
    
    std::string query("select logged from login where id = " +
                      boost::lexical_cast<std::string>(ClientID));
    

더 많은 것을 위해 int를 char *로 캐스팅 할 수 없습니다. 이 시도 :

std::ostringstream sstream;
sstream << "select logged from login where id = " << ClientID;
std::string query = sstream.str();

stringstream 참조


ClientID함수가 null 종료 문자 배열을 가정하도록하는 char * 로 캐스팅 하고 말할 것입니다.

cplusplus.com에서 :

확장 & 추가 (const char * s); s가 입구 Null 종료 문자 시퀀스 (C 노드)로 노드의 복사본을 추가합니다. 이 문자 시퀀스의 길이는 null 문자의 첫 번째 발생에 의해 결정됩니다 (traits.length (s)에 의해 결정됨).


나는 당신 ClientID이 이끄는 유형 (0으로 끝나는 char*또는 std::string)이 아니라 일부 정수 유형 (예 :) 이 아니라는 느낌이 있기 때문에 먼저 int숫자를 번역해야합니다.

std::stringstream ss;
ss << ClientID;
query.append(ss.str());

그러나 operator+(대신 append) 사용할 수도 있습니다 .

query += ss.str();

참고 URL : https://stackoverflow.com/questions/10516196/append-an-int-to-a-stdstring

반응형