Nice programing

C ++에서 문자열을 인쇄하는 방법

nicepro 2020. 12. 10. 21:10
반응형

C ++에서 문자열을 인쇄하는 방법


나는 이것을 시도했지만 작동하지 않았습니다.

#include <string>
string someString("This is a string.");
printf("%s\n", someString);

#include <iostream>
std::cout << someString << "\n";

또는

printf("%s\n",someString.c_str());

기본 버퍼에 액세스해야합니다.

printf("%s\n", someString.c_str());

또는 더 나은 사용 cout << someString << endl;( #include <iostream>사용해야 함 cout)

또한 당신은 가져올 수 std사용하여 네임 스페이스를 using namespace std;또는 둘 모두 접두사 stringcout함께를 std::.


당신은 필요 #include<string>사용 string#include<iostream>사용 cincout. (내가 답을 읽을 때 그것을 얻지 못했습니다). 작동하는 코드는 다음과 같습니다.

#include<string>
#include<iostream>
using namespace std;

int main()
{
    string name;
    cin >> name;
    string message("hi");
    cout << name << message;
    return 0;
}

매개 변수에 std :: string을 사용하여 "printf"를 호출 할 수 없습니다. "% s"는 C 스타일 문자열 : char * 또는 char [] 용으로 설계되었습니다. C ++에서는 다음과 같이 할 수 있습니다.

#include <iostream>
std::cout << YourString << std::endl;

printf 절대적 으로 사용하고 싶다면 문자열의 char * 표현을 제공하는 "c_str ()"메서드를 사용할 수 있습니다.

printf("%s\n",YourString.c_str())

을 사용 printf()하려는 경우 다음을 수행 할 수도 있습니다.

#include <stdio.h>

문자열을 사용하는 동안 메시지를 인쇄하는 가장 좋은 방법은 다음과 같습니다.

#include <iostream>
#include <string>
using namespace std;

int main(){
  string newInput;
  getline(cin, newInput);
  cout<<newInput;
  return 0;
}


이것은 채택한 방법을 수행하는 대신 단순히 작업을 수행 할 수 있습니다.

참고 URL : https://stackoverflow.com/questions/5322216/how-to-print-a-string-in-c

반응형