时间: 2020-09-19|tag:56次围观|0 条评论

一、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!

本博客所有文章如无特别注明均为原创。
复制或转载请以超链接形式注明转自起风了,原文地址《C风格字符串和C++风格字符串转换
   

还没有人抢沙发呢~