Just a Computer Graphics Studio & My Life

處理檔案資料,最常使用char[]string來儲存字串,前者是字元陣列,為C所擁有,當然C++也可以使用;而後者是C++獨有的字串類別,可以產生字串物件。

在使用C++處理字串時,時常會char[]string互轉,來符合接下來要使用的函式中參數的型態,假如可以互轉自如,那麼處理起檔案資料會更簡單便利喔!

我測試的程式碼如下:

/**
	Theme: string & char[] transform
	Compiler: Dev C++ 4.9.9.2
	Date: 100/05/01
	Author: ShengWen
	Blog: https://cg2010studio.wordpress.com/
*/
#include<iostream>
using namespace std;
int main(){
	string test_string="test_string";
	char test_char[]="test_char", result_char[20];

	string result_string1(test_char);
	string result_string2;
	result_string2.assign(test_char);
	strcpy(result_char, test_string.c_str());

	cout<<"test_string: "<<test_string<<endl;
	cout<<"test_char: "<<test_char<<endl;
	cout<<"result_string1: "<<result_string1<<endl;
	cout<<"result_string2: "<<result_string2<<endl;
	cout<<"result_char: "<<result_char<<endl;

	system("pause");
	return EXIT_SUCCESS;
}

程式結果為:

test_string: test_string
test_char: test_char
result_string1: test_char
result_string2: test_char
result_char: test_string
請按任意鍵繼續 . . .

可見到stringchar[]相當簡單,只要呼叫string class的成員函式c_str(),即可將string轉為char[]
那麼char[]string呢?有兩種方法,第一種是初始string變數時,即把char[]當作參數來初始化,第二種則是使用string class的成員函式assign(char[])來將char[]指定為string變數。

廣告

Comments on: "[C++] string 和 char[]互轉 (string and char[] transform)" (7)

  1. penumbuh rambut said:

    Excellent article! We are linking to this great content on our website.
    Keep up the good writing.

    喜歡

  2. Hello are using WordPress for your blog platform? I’m new to the blog world but I’m trying to get started and create my own. Do you require any html coding expertise to make your own blog? Any help would be really appreciated!

    喜歡

  3. I don’t drop a comment, however after reading a few of the comments on this page [C++] string 和 char[]互轉 (string and char[] transform) | 逍遙文工作室. I actually do have some questions for you if you don’t mind.
    Could it be just me or does it look like some of these remarks come across like they are left by brain dead folks? 😛 And, if you are posting at additional sites, I would like to keep up with you. Would you list of all of your social sites like your linkedin profile, Facebook page or twitter feed?

    喜歡

  4. […] 就如同string 和 char[]互轉這篇文章一樣,時常需要將字串來回轉換,在OpenCV中處理對象為影像,有時也需要來回轉換,於是我想記錄一下:P […]

    喜歡

  5. […] [C++] string 和 char[]互轉 (string and char[] transform) […]

    喜歡

發表留言

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

您的留言將使用 WordPress.com 帳號。 登出 / 變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 / 變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 / 變更 )

Google+ photo

您的留言將使用 Google+ 帳號。 登出 / 變更 )

連結到 %s

標籤雲

%d 位部落客按了讚: