c++ trap: the character array & string

#include <iostream>
#include <string>

int main()
{
    using namespace std;
    char charr1[20];
    char charr2[20] = "jaguar";
    string str1;
    string str2 = "panther";

    cout << "Enter a kind of feline: ";
    cin >> charr1;
    cout << "Enter another kind of feline: ";
    cin >> str1;
    cout << "Here are some felines:\n";
    cout << charr1 << " " << charr2 << " "
        << str1 << " " << str2 << endl;
    cout << "The third letter in " << charr2 << " is "
        << charr2[2] << endl;
    cout << "The third letter in " << str2 << " is "
        << str2[2] << endl;
    return 0;
}

The mechanism of string operation is different to the C-style. Although you can initialize a string object to a C-style string.In this program tell us some facts we need to know. Cin can store keyboard input in a string object, just as the definition of string. "cout" can directly display a string object. If you like another way, okay, we can display the string like the character array.  the irreversible behavior of C-style. I think that's important to know how to store the string in C++ circumstance?

#include <iostream>

#include <string>

int main()

{

 string str2 = "Hello"

cout << "The size of str2: " << sizeof str2 << endl;

cout << "The second letter in str2: " << str2[1] << endl;

return 0;

}

The pointer behavior: 4 bytes. ?? the same concept in python... (Acctually, we need more information about it)

the next process tell me. str.size() return the length of string as the same as the strlen(str).

Noting in my mind right now.. continue...

The books says:

Conceptually, one thinks of an array of char as a collection of char storage units used to store a string but of a string class variable as a single entity representing the string.

C++98:

default (1)
string();
copy (2)
string (const string& str);
substring (3)
string (const string& str, size_t pos, size_t len = npos);
from c-string (4)
string (const char* s);
from sequence (5)
string (const char* s, size_t n);
fill (6)
string (size_t n, char c);
range (7)
template <class InputIterator>
  string  (InputIterator first, InputIterator last);


c++11:

default (1)
string();
copy (2)
string (const string& str);
substring (3)
string (const string& str, size_t pos, size_t len = npos);
from c-string (4)
string (const char* s);
from buffer (5)
string (const char* s, size_t n);
fill (6)
string (size_t n, char c);
range (7)
template <class InputIterator>
  string  (InputIterator first, InputIterator last);
initializer list (8)
string (initializer_list<char> il);
move (9)
string (string&& str) noexcept;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值