본문 바로가기
TIL,WIL

til - 20250329

by GREEN나무 2025. 3. 29.
728x90

오늘 한일

💠코드카타
  SQL 8번 : https://ashen99.tistory.com/698
  SQL 9번 : https://ashen99.tistory.com/699
  SQL 10번 : https://ashen99.tistory.com/700

  C++ 11번 : https://ashen99.tistory.com/254
  C++ 12번 : https://ashen99.tistory.com/256

오늘 중요한 것을 정리하면서 기억할 필요가 있는 것 1~2가지

 

✅ C++에서 std::string을 printf로 출력하려고 하면 발생하는 "std::string"에서 "const char *"로의 적절한 변환 함수가 없습니다. 오류 해결방법

🔍 원인 :

  • printf 함수는 const char* 형식의 문자열을 기대하지만, std::string은 이를 자동 변환하지 않음.
  • 따라서 std::string을 printf로 직접 출력하면 컴파일 오류 발생.

🛠 해결 방법:

  1. c_str() 사용하여 const char*로 변환
  2. printf("%s", solution11(3).c_str());
  3. cout을 사용하여 출력 (권장)
    • cout은 std::string을 자동으로 처리 가능하므로 더 간단하고 가독성이 좋음.
  4. cout << solution11(3) << endl;

최종 코드 수정 예시:

#include <iostream>
#include <string>

using namespace std;

string solution11(int num)
{
    return num % 2 ? "Odd" : "Even";
}

int main()
{
    cout << solution11(3) << endl;  // 권장 방법
    // printf("%s", solution11(3).c_str());  // printf를 꼭 써야 한다면 이렇게
}

 

 

참고

https://blockdmask.tistory.com/475

 

 

'TIL,WIL' 카테고리의 다른 글

Til - 20250331  (0) 2025.03.31
TIL - 20250330  (0) 2025.03.30
250207 - 로드 밸런싱  (0) 2025.02.07
TIL 250102  (0) 2025.01.02
TIL 241227  (1) 2024.12.27