zoukankan      html  css  js  c++  java
  • converting char array to string type

    std::string str;
    char array[] = "Hello World";
    for(int i = 0; array[i] != 0; i++)
       str 
    += array[i];
    //-----------------------------------
    std::string str;
    char array[] = "Hello World";

    str 
    = array;
    Use of NULL is discouraged in C++ because it can be redefined to be anything one wants -- c++ standards do not dictate what NULL should be.

    The '\0' and 0 are one in the same thing. The compiler will translate '\0' to 0 during compilation.

    All C-style strings are said to be NULL-terminated -- that definition is carry-over from C language. It really means that the end of the string is indicated by the byte which contains a 0.

    you cannot assign C-strings that have enbedded 0s to std::string as I posted earlier. As you found out the assignment stops at the first 0. You could do it one character at a time, but then std::string is no longer an ascii string but a binary string, and most of the std::string methods cannot be used, again because of embedded 0s.

    In this example, the output of the first cout is jest "Hello" because of the embedded 0.
    #include <string>
    #include 
    <iostream>
    using namespace std;

    int main()
    {
        
    int i;
        
    char str[] = "Hello \0World";
        
    string s = str;
        cout 
    << s << endl; << output = "Hello"
        
    int sz = sizeof(str);
        s 
    = "";
        
    for(i = 0; i < sz; i++)
            s 
    += str[i];

        cout 
    << s << endl;
     
    // now assign characters one at a time
        sz = s.length();
        
    for(i = 0; i < sz; i++)
            cout 
    << s[i];
        cout 
    << endl; output = "Hello World" 
        
    return 0;

    } 

    int main()
    {
        
    int i;
        
    string s;
        
    char str[] = "Hello \0World";
        
    int sz = sizeof(str);
        s.assign(str,sz);
        sz 
    = s.length();
        
    for(i = 0; i < sz; i++)
            cout 
    << s[i];
        cout 
    << endl;
        
    return 0;

    } 

  • 相关阅读:
    js实现好看的图案 加勒比海盗(php拍黄片)
    网站优化的几点 下
    php算法 快速排序 选择算法 冒泡算法
    javascript中null和undefined的区别
    tp3 上传图片出现上传根目录不存在!请尝试手动创建:./Public/Uploads/ 错误解决思路
    网站优化的几点 上
    tp5框架 报错非法请求:admin/index/index
    通过response向服务器用Io流写入图片
    解决客户端向服务器写中文时乱码问题
    setInterval()设置页面5,4,3,2,1秒后跳转
  • 原文地址:https://www.cnblogs.com/smartvessel/p/2044040.html
Copyright © 2011-2022 走看看