c++ - 在 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;
}
解决方案
在您的情况下,s2
初始化为长度为 0 的空字符串,因此您不能超出范围。如果你想,你必须先调整它的大小:
s2.resize(s1.length());
for(i=0; s1[i]!='\0'; ++i)
{
s2[i]=s1[i];
}
此外,与 C 字符串不同,c++std::string
不需要终止空字节。
推荐阅读
- excel - 添加项目后VBA删除行
- python - 如何使用 selenium 抓取表数据?
- node.js - MongooseError:操作 `guild-prefixes.findOne()` 缓冲在 10000 毫秒后超时 discord.js
- javascript - BrowserAuthError:interaction_in_progress - 无法修复,无论找到什么解决方案
- arduino - 液晶显示器上的随机移动字符
- android - Ionic Cordova 对新的 Android Bundle 构建感到困惑
- html - 卡片在主标签内未正确显示
- c# - 绘制 3D 矩形,为您单击的每一侧执行不同的操作
- sql - 在 Hive 视图中屏蔽子字符串
- java - Java 语法和逻辑帮助“?” 和 ”:”