處理檔案資料,最常使用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
請按任意鍵繼續 . . .
可見到string轉char[]相當簡單,只要呼叫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)
Excellent article! We are linking to this great content on our website.
Keep up the good writing.
讚讚
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!
讚讚
Yes, I am using WordPress to blog. But I have no time to learn to make my own blog by using html coding. Thank you for giving me the information. 🙂
讚讚
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?
讚讚
Thank you for admiring!!
My twitter: https://twitter.com/HappyMan_Chiou
Welcome to follow me. 😀
By the way, where are you from?
And your social network link?
讚讚
[…] 就如同string 和 char[]互轉這篇文章一樣,時常需要將字串來回轉換,在OpenCV中處理對象為影像,有時也需要來回轉換,於是我想記錄一下:P […]
讚讚
[…] [C++] string 和 char[]互轉 (string and char[] transform) […]
讚讚