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;

    } 

  • 相关阅读:
    SQL Server 2005 全文搜索包括改进和更新的干扰词文件FROM MS KB
    服务器内存选项From MS
    跳过事务复制中的错误
    WP7基础补充
    TaoBaoAPI简介3
    登录功能代码
    TaoBaoApI简介1
    TaoBaoAPI简介2
    WP7基础学习第十三讲
    WP7基础学习第十四讲
  • 原文地址:https://www.cnblogs.com/smartvessel/p/2044040.html
Copyright © 2011-2022 走看看