1 条题解

  • 0
    @ 2025-3-8 16:17:51
    /*
    思路分析
    思路一(error) : 直接用sizeof(string)
                 ——sizeof计算的是string对象本身的大小,
                 ——而不是它所存储的字符串内容的大小。
    
    思路二(error): 用string接收,用char c : stirng遍历
                 —— 统计出来的只是字符的大小空间
                 ——结尾的\0没有统计到
    
    学习思路三(yes): 用字符数组接收 
                        再用sizeof 直接得到完整大小
    
    
    #include <bits/stdc++.h>
    using namespace std;
    
    int main()
    {
        string s;
        size_t m = 0;
        s = "Hello, World!";
        for ( char c : s) { //cahr c : s  ==> 只能用于for不能用于while
            m += sizeof(c);
        }
        cout << m + 1; //加上末尾的空字符\0
        return 0;
    }
    
    #include <bits/stdc++.h>
    using namespace std;
    
    int main()
    {
        char str[] = "Hello, World!";
        cout << sizeof(str);
    
        return 0;
    }
    
    /*
    空字符(\0) 是一个特殊的字符,其ASCII码值为0。
    在C风格字符串中,空字符\0是必须的,因为它用于标记字符串的结束位置。
    C风格字符串的定义:一个以空字符\0结尾的字符数组。
    */
    
    */
    
    • 1

    信息

    ID
    35
    时间
    1000ms
    内存
    256MiB
    难度
    6
    标签
    递交数
    55
    已通过
    16
    上传者