이것은 C++에서 string을 char 배열로 변환하는 C++ 프로그램입니다. 여러 가지 방법으로 수행할 수 있습니다.
유형1
알고리즘
Begin Assign a string value to a char array variable m. Define and string variable str For i = 0 to sizeof(m) Copy character by character from m to str. Print character by character from str. End
예시
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char m[]="Tutorialspoint";
string str;
int i;
for(i=0;i<sizeof(m);i++)
{
str[i]=m[i];
cout<<str[i];
}
return 0;
} 유형 2
strcpy() 함수를 호출하여 문자열을 char 배열에 복사할 수 있습니다.
알고리즘
Begin Assign value to string s. Copying the contents of the string to char array using strcpy() . End
예시
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
string str = "Tutorialspoint";
char c[str.size() + 1];
strcpy(c, str.c_str());
cout << c << '\n';
return 0;
} 출력
Tutorialspoint
유형3
기본적으로 c에서 std::string::copy 대신 사용되는 strcpy() 사용을 피할 수 있습니다.
알고리즘
Begin Assign value to string s. Copying the contents of the string to char array using copy(). End
예시
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "Tutorialspoint";
char c[str.size() + 1];
str.copy(c, str.size() + 1);
c[str.size()] = '\0';
cout << c << '\n';
return 0;
} 출력
Tutorialspoint