• Tistory
    • 태그
    • 위치로그
    • 방명록
    • 관리자
    • 글쓰기
Carousel 01
Carousel 02
Previous Next

std::string에서 format을 사용하자

Programming/C, C++, MFC 2020. 3. 19. 11:31




std::string을 사용하다보면 sprintf나 CString 등과 같이 format 기능을 이용하여 문자열을 만들고싶을떄가 있다.

 

이런 상황을 위한 방법을 정리.

 

아래와 같이 정의된 string_format 함수를 이용하여 format 과 동일하게 사용 가능하다. 

 


template<typename ... Args>
std::string string_format(const std::string& format, Args ... args)
{
	size_t size = snprintf(nullptr, 0, format.c_str(), args ...) + 1; // Extra space for '\0'
	if (size <= 0) { throw std::runtime_error("Error during formatting."); }
	std::unique_ptr<char[]> buf(new char[size]);
	snprintf(buf.get(), size, format.c_str(), args ...);
	return std::string(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside
}


// 사용법
std::string sResult = "";
std::string stringValue = "string...";
int intValue = 999;
sResult = string_format("string format example : %s / %d", stringValue, intValue);
저작자표시 (새창열림)

'Programming > C, C++, MFC' 카테고리의 다른 글

MFC Dialog 에서 enter, esc 동작을 제어하자  (0) 2020.11.10
하위폴더 포함, 폴더 전체를 복사하자  (0) 2020.11.10
CStdioFile 을 이용한 파일 입출력에서 내용이 깨질경우  (0) 2019.07.09
Unicode 환경에서 한글이 깨질경우 해결방법  (0) 2019.03.11
cout을 이용할때 출력 정밀도를 제어해 보자  (0) 2018.07.26
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

카테고리

  • 살다보니.. (451)
    • 주절거림 (3)
    • 취미생활 (36)
      • 지식과 지혜 (3)
      • 풍경이 되어 (4)
      • Memories (17)
      • 엥겔지수를 높여라 (2)
    • mathematics (6)
      • Matrix Computation (2)
      • RandomProcesses (3)
    • English.. (8)
    • Programming (147)
      • C, C++, MFC (51)
      • C# (1)
      • OpenCV (17)
      • Python (58)
      • Git, Docker (3)
      • Matlab (4)
      • Windows (3)
      • Kinect V2 (2)
      • 기타 etc. (8)
    • 전공관련 (80)
      • Algorithm (6)
      • Deep Learning (54)
      • 실습 프로그램 (4)
      • 주워들은 용어정리 (8)
      • 기타 etc. (8)
    • Computer (121)
      • Utility (21)
      • Windows (31)
      • Mac (4)
      • Ubuntu, Linux (61)
      • NAS (2)
      • Embedded, Mobile (2)
    • IT, Device (41)
      • 제품 사용기, 개봉기 (14)
      • 스마트 체험단 신청 (27)
    • Wish List (3)
    • TISTORY TIP (5)
    • 미분류. 수정중 (1)

태그목록

  • 매트랩 함수
  • LIBSVM
  • DeepLearning
  • SVM
  • ReadString
  • 스마트체험단
  • matlab
  • 후쿠오카
  • matlab function
  • 에누리닷컴
  • 일본
  • Convolutional Neural Networks
  • 오봉자싸롱
  • 매트랩
  • random variable
  • 칼로리 대폭발
  • 딥러닝
  • Deep Learning
  • 큐슈
  • CStdioFile
  • 포르투갈
  • DSLR
  • Computer Tip
  • ColorMeRad
  • utility
  • review
  • function
  • 갤럭시노트3
  • 크롬
  • portugal

달력

«   2026/02   »
일 월 화 수 목 금 토
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
02-20 05:56

LATEST FROM OUR BLOG

RSS 구독하기

BLOG VISITORS

  • Total :
  • Today :
  • Yesterday :

Copyright © 2015 Socialdev. All Rights Reserved.

티스토리툴바