c++ - cout of string 不显示任何内容
问题描述
字符串的 coutencrypted
不显示任何内容,有时程序会崩溃。当我cout << encrypted[i]
在 for 循环中做时,我得到了正确的结果。此外,如果我执行一个 for 循环以按 char 读取字符串 char for(char c:encrypted)
,cout << c << endl;
=> 它也不起作用并得到垃圾。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
string key = "XZNLWEBGJHQDYVTKFUOMPCIASRxznlwebgjhqdyvtkfuompciasr";
string encrypted;
string decrypted;
string message;
int pos{};
cout << "enter the message" << endl;
getline(cin,message);
//encrypting
for (size_t i{} ;i<message.length();i++)
{
if (alphabet.find(message[i]) != string::npos)
{pos = alphabet.find(message[i]);
encrypted[i] = key[pos];
}else
{encrypted[i]=message[i];
cout << encrypted[i];
}
}
cout << "the encrypted message is: "<< encrypted << endl;
解决方案
Afterstring encrypted;
encrypted
默认初始化为空std::string
,不包含任何元素。encrypted[i]
然后对不存在的元素(如导致 UB)的任何访问。
您可以改用push_back
(或operator+=
)。
//encrypting
for (size_t i{}; i<message.length(); i++)
{
if (alphabet.find(message[i]) != string::npos)
{
pos = alphabet.find(message[i]);
encrypted.push_back(key[pos]);
}
else
{
encrypted.push_back(message[i]);
cout << encrypted[i];
}
}
或者提前encrypted
用元素初始化。message.length()
getline(cin,message);
string encrypted(message.length(), '\0'); // initialize encrypted as containing message.length() elements with value '\0'
//encrypting
for (size_t i{}; i<message.length(); i++)
{
...
推荐阅读
- javascript - 如何在侧模板标签中调用 vue.js 方法并显示方法返回数据
- javascript - 从 JSP/Ajax 中填充的带有按钮的清除下拉 Select2 只能工作一次
- tomcat - Artifactory 7.x 上的网络上下文
- python - 通过循环创建对象
- vue.js - Vue - 存储数据最佳实践
- python - bigARTM 安装:Cmake 找不到 Boost
- docker - DOCKER 如何使用 Windows 映像在 docker run 上设置密码和用户名?
- c++ - 如何使用 GCC 读取 .s 文件?
- android - Android中cmake的路径
- vba - 任务完成时发送电子邮件 - 新方法