首页 > 解决方案 > 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;

标签: c++string

解决方案


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++)
{
    ...

推荐阅读