簡體   English   中英

我的 C++ 應用程序在輸入一個值(std::cin >> 值)后關閉,我不知道為什么

[英]My C++ application closes after entering a value (std::cin >> value) and I don't know why

我有 4 個函數: encrypt()decrypt()generate_key()menu()

菜單只是詢問用戶要執行什么操作,並使用 if 和 else 是否會像這樣執行所選的 function:

if (choice == 1) {
   encrypt();
   
   menu();
}

所以會發生的是encrypt() function 應該首先執行,在它執行完后,它將 go 通過調用menu() function 返回菜單。

現在這是我的encrypt() function:

    int encrypt() {
    // Ask the user for a message to encrypt and the key to use
    std::cout << "Enter a message to encrypt: ";
    std::string message;
    std::cin >> message;
    
    std::cout << "Enter a key to use: ";
    int key;
    std::cin >> key;
    
    // Encrypt the message
    std::string encryptedMessage = "";
    for (int i = 0; i < message.length(); i++) {
        encryptedMessage += (message[i] + key);
    }
    
    // Print the encrypted message
    std::cout << "Encrypted message: " << encryptedMessage << std::endl;
    
    return 0;
    }

從你在這里看到的,程序應該請求一條消息,用戶輸入一條消息,然后請求密鑰並輸入一個密鑰,然后它會“加密”消息並打印出來。 但是發生的事情是它要求一條消息,然后在用戶輸入一條消息后,要求輸入密鑰,但是當您輸入密鑰時,應用程序就關閉了,沒有任何錯誤消息,什么也沒有。 我真的很無能,不知道我做錯了什么。

這是我的完整代碼: https://paste.ubuntu.com/p/NdVTKmcg9J/

你不能只在 c++ 中將 char 添加到字符串中,你必須使用 stringstream

#include <sstream>
int encrypt() {
    // Ask the user for a message to encrypt and the key to use
    std::cout << "Enter a message to encrypt: ";
    std::string message;
    std::cin >> message;

    std::cout << "Enter a key to use: ";
    int key;
    std::cin >> key;

    std::stringstream encryptedMessage;
    for (int i = 0; i < message.length(); i++) {
        encryptedMessage << (message[i] + key); // "add" the result to stream
    }

    // Print the encrypted message
    std::cout << "Encrypted message: " << encryptedMessage.str() /*build the string*/ << std::endl;

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM