首页 > 解决方案 > 在 C++ 中执行字符串复制操作时出错

问题描述

请解释为什么这是一个错误,但另一个运行正常以下代码给出了错误:

#include <iostream>
#include <string>
#include <conio.h>
#include <math.h>
#include <iomanip>
#include <string.h>

using namespace std;

int main()
{
    string s1,s2;
    int i;

    cout << "Enter the string to copy into another string : ";
    getline(cin,s1);

    for(i=0; s1[i]!='\0'; ++i)
    {
      s2[i]=s1[i];
    }
    s2[i]='\0';
    cout<<"\n\nCopied String S2 is : "<<s2;
    return 0;
}

错误看起来像这样

错误看起来像这样

但这工作得很好

#include <iostream>
#include <string>
#include <conio.h>
#include <math.h>
#include <iomanip>
#include <string.h>

using namespace std;

int main()
{
    char s1[100], s2[100], i;

    cout << "Enter the string to copy into another string : ";
    cin>>s1;

    for(i=0; s1[i]!='\0'; ++i)
    {
      s2[i]=s1[i];
    }
    s2[i]='\0';
    cout<<"\n\nCopied String S2 is : "<<s2;
    return 0;
}

标签: c++

解决方案


在您的情况下,s2初始化为长度为 0 的空字符串,因此您不能超出范围。如果你想,你必须先调整它的大小:

s2.resize(s1.length());
for(i=0; s1[i]!='\0'; ++i)
{
    s2[i]=s1[i];
}

此外,与 C 字符串不同,c++std::string不需要终止空字节。


推荐阅读