C风格字符串和C++风格字符串转换

一、C风格—>C++风格

    char c[] = "hello world";
    string s(c);

    cout << s << endl;  //hello world

二、C++风格—>C风格

    int i;
    string s = "hello world";
    const char *p = s.c_str();  //const不能省去!

    for (i = 0; i < s.length(); i++) {
        cout << p[i];  //hello world
    }

三、C和C++在终端获取一整行字符串

C++中:

string s;
getline(cin, s);

getline会读取一整行字符串(包括空格),而如果使用: cin >> s; 那么遇到空格将停止读取。

C中:

char c[100];
gets(c);

gets也会读取空格。利用puts输出即可。而如果使用: scanf(“%s”, c); 也是遇到空格停止读取。


结语:文章有错误或不足,欢迎评论,希望轻拍,一起进步哦!

END!

猜你喜欢

转载自blog.csdn.net/qq_41139830/article/details/80625186
今日推荐