#include <iostream>
#include <string>
using namespace std;
int main()
{
const char *st = "12";
cout << sizeof(st) << endl; //print the size of pinter!
string s1 = "123";
cout << sizeof(s1) << endl; //still not the actual length
cout << s1.size() << endl; //number of characters, excluding '\0'
cout << s1.length() << endl;//same
cout << strlen(s1.c_str()) << endl; //same
cout << sizeof("123") << endl; //print 4, including '\0'
//convert C++ string to C string
char *not_right = s1.c_str(); //compile error, s1.c_str() is type
// (const char*) not (char*)
//--------------------------------------------------
// C-style strings
//p.90, B.S.
char s[] = "asdf";
cout << strlen(s) << endl; //print 4, excluding '\0'
cout << sizeof(s) << endl; //print 5, includeing '\0'
char *weird = "Trick or treat?"; //implicit const_cast by c++
//for c compatibility or we will
//break million lines of code
weird[1] = 'a'; //error: assignment to const; result is undefined
//if you really want to modifiy it,
//make the string guarantee to be able to modify
char p[] = "ok now";
p[0] = 'a'; //ok!
}
Search This Blog
Tuesday, June 9, 2009
string and const in C and C++
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment