c++ - 为什么 C++ 中 std::string 的复制方法在此程序中显示出奇怪的行为?

#include<iostream>
using namespace std;
int main() 
{
    string str1 = "geeksforgeeks is for geeks";   
    string str2 = "geeksforgeeks is for geeks";

    char ch1[100];
    char ch2[100];
 
    cout<<str1.size()<< endl << endl;
    str1.copy(ch1,23,0);
    str2.copy(ch2,24,0);
    
 
    cout << ch1 << endl << endl;
    cout << ch2 << endl << endl;
    


    return 0;

}

字符串的长度是 26,当我试图复制超过 23 个字符时,它表现出奇怪的行为(最后打印随机字符) 这是上面程序的输出

26

geeksforgeeks is for ge

geeksforgeeks is for gee£qí╜∙⌂

最佳答案

这是因为您没有设置任何'\0'(空)字符来确定结束。这就是它拾取垃圾值(value)的原因。

你可以做到

#include<iostream>
using namespace std;
int main() 
{
    string str1 = "geeksforgeeks is for geeks";   
    string str2 = "geeksforgeeks is for geeks";

    char ch1[100];
    char ch2[100];
 
    cout<<str1.size()<< endl << endl;
    str1.copy(ch1,23,0);
    str2.copy(ch2,24,0);
    
    ch1[23] = '\0';  
    ch2[24] = '\0';  
 
    cout << ch1 << endl << endl;
    cout << ch2 << endl << endl;
    


    return 0;

}

https://stackoverflow.com/questions/67615709/

相关文章:

java - 如何断言数组中某个值的存在

pandas - 如何通过每行的第一个单词将 pandas 中的行汇总为该第一个单词的聚合?

r - 使用 melt 将数据合并到一个长列中

python - 如何从 yfinance 数据中删除时区?

typescript - 没有泛型的类型推断?

c# - 在不使用 lambda 表达式的情况下从该方法传递额外参数时在方法内部订阅事件

android - Jetpack 撰写 : Textfield and FAB not using

python - 无需替换即可生成置换数组

c# - 如何将普通字符串转换为十六进制的等效字节数组?

kubernetes - Helm : How to avoid recreating secret