string 객체의 문자열을 포인터의 대상체로 복사하는 방법 없을까요?

dltkddyd의 이미지

string 클래스로 만든 객체의 내용을 포인터의 대상체로 복사해 사용해야 합니다. 그래서 다음과 같이 했더니 작동이 안되네요.

string a="Recent";
char* ap=new char[a.length()+1];
strcpy(ap,a);
cout<<ap;

cout으로 Recent라는 문자열을 출력하려 했는데 안됩니다. string 타입의 문자열을 어떻게 포인터 대상체로 넣나요?
그리고 저 문자열 Recent를 직접 strcpy로 ap의 대상체에 집어넣을 방법은 없을까요? 다음과 같이요.

strcpy(ap,"Recent);

gilgil의 이미지

strcpy(ap,a);

strcpy(ap,a.c_str());
로 바꿔 주세요.

start with zero인 문자열 배열과 string 클래스 객체는 다릅니다.

dltkddyd의 이미지

그러면 문자열을 일반 타입처럼 대입할 수 없는 건가요? 문자열 상수도 포인터를 반환하는 것으로 알고 있습니다. 가령

"gogo"

라는 문자열은 포인터를 반환해 돌려주는 것으로 알고 있었는데, 그게 아닌가요?

char *t=(char*)"gogo";

이런 것이 가능하던데요, "gogo" 상수는 포인터 아닐까요?

본인 맞습니다.
인증샷
우헤헤헤... 로 대신합니다.

gilgil의 이미지

기본적으로 C/C++ code에서 문자열은 character pointer로 인식을 합니다.

char* s = "foo"; // 말씀하셨듯이 포인터의 위치가 s라는 변수에 할당이 됩니다.

string s = "foo"; // 이는 string(const char* rhs) 와 같은 constructor가 호출이 됩니다.

C++에서는 string이라는 기본 type이 존재하지 않기 때문에 constructor 및 operator를 overriding을 이용하고 있습니다.

dltkddyd의 이미지

#include
using namespace std;

int main() {
char* s="gogo";
cout<<s<<endl;
}

위와 같이 하면 컴파일 시

string 상수에서 char*로 기능이 저하된 변환이라며 에러메시지가 뜹니다.

#include
using namespace std;

int main() {
char* s=(char*)"gogo";
cout<<s<<endl;
}

이렇게 해야 되더군요.

본인 맞습니다.
인증샷
우헤헤헤... 로 대신합니다.

dltkddyd의 이미지

문자열을 다루는 사용자정의 클래스에서 문자열 생성자를 오버로딩하기 위해서입니다. 가령 문자열을 다루는 YString이라는 클래스가 있는데, 그 중 어떤 생성자가 다음과 같습니다.

class YString {
private:
char* myStr;
public:
YString(char* str) {
len=strlen(str);
myStr=new char[len+1];
strcpy(myStr,str);
}
void output() {
cout<<myStr;
}
};

void main() {
YString myS=(char*)"You win!";
output();
}

그런데 에러가 납니다.

main 함수

YString myS=(char*)"You win!";

부분은 이렇게 해석되지 않나요.

YString myS((char*)"You win!");

그러면 생성자 YString(char* str)이 호출되어 문자열의 깊은 복사가 이루어져야 할텐데, 지금 컴파일부터 안되고 있다는 것이 문제입니다.

본인 맞습니다.
인증샷
우헤헤헤... 로 대신합니다.

peecky의 이미지

"string" 문자열은 const char* 타입입니다.

class YString {
public:
YString(const char* str) {
}
};
으로 해보세요

dltkddyd의 이미지

대응되는 함수가 없다는 컴파일 에러가 출력됩니다.

본인 맞습니다.
인증샷
우헤헤헤... 로 대신합니다.

dltkddyd의 이미지

YString myS((char*)"You win!");

위와 같이는 당연히 됩니다.

그러나 정작 원하는 변환생성자는 초기화와 동시에 문자 할당이 이루어지는 생성자입니다. 다음과 같이 말이죠.

YString myS=(char*)"You win!";

마치

int s=25;

이런 식으로 선언과 초기화가 가능하듯이 말입니다.

본인 맞습니다.
인증샷
우헤헤헤... 로 대신합니다.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.