2014-11-02 69 views
0

我正在编写一个代码来加密凯撒密码中输入的文本,但我遇到了问题。在运行我的代码时,我的循环没有在空字符处终止。代码如下:打印字符数组时接收垃圾值

#include <iostream> 
using namespace std; 

void main() 
{ 
    char message[200], en_message[200]; 

    cout << "Enter your message to encrypt: "; 
    std::cin.getline(message,200); 

    for (int index = 0 ; message[index] != '\0' ; index++) 
    { 
     if (message[index] == 'A') 
      en_message[index] = 'X'; 

     else if (message[index] == 'B') 
      en_message[index] = 'Y'; 

     else if (message[index] == 'C') 
      en_message[index] = 'Z'; 

     else 
      en_message[index] = message[index] - 3; 
    } 

     cout << en_message; 
} 

我曾尝试: “!en_message [索引] = '\ 0'”

1)使用一个循环输出数组 “en_message” 与 使用和“en_message [index]!=''“作为for循环中的条件

2)使用if条件来中断循环。

无论我尝试什么,我都会得到这个输出! 1

任何帮助,将不胜感激。感谢所有提前。

编辑: 好吧,所以现在我得到另一个问题。我在我大学的实验室计算机上试过G ++编译器中的代码,它运行正常,但在家中,我收到了这个错误“运行时检查失败#2.围绕变量'en_message'的堆栈已损坏。”我正在使用Visual Studio 2010。那可能是什么?修改后的代码是:

#include<iostream> 
using namespace std; 

void main() 
{ 
    char message[200], en_message[200]; 
    int index; 

    cout << "Enter your message to encrypt: "; 
    cin >> index; 

    for (index = 0 ; index < 200 ; index++) 
    { 
     if (message[index] == '\0') 
      break; 

     if (message[index] == 'A') 
      en_message[index] = 'X'; 

     else if (message[index] == 'B') 
      en_message[index] = 'Y'; 

     else if (message[index] == 'C') 
      en_message[index] = 'Z'; 

     else 
      en_message[index] = message[index] - 3; 
    } 
    en_message[index] = '\0'; 


    cout << en_message; 
} 
+3

看看,http://stackoverflow.com/questions/2037209/what-is-a-null-terminated-string。您在加密字符串的末尾忘记'\ 0'。 – 2014-11-02 07:50:02

+0

您如何期待输出程序知道何时停止? – 2014-11-02 08:26:22

+0

而不是创建任意大小的数组,为什么不使用向量或只有正确大小所需的字符串? – 2014-11-05 14:55:33

回答

1

你的代码是做正确的你正在缩进要做什么,但是你没有得到正确的输出,因为你没有终止你的字符串。 210试试这个: -

int index; 
for (index = 0 ; message[index] != '\0' ; index++) 

和这个循环之后,你需要确保

en_message[index] = '\0'; 

一件事是,你必须考虑到只有大写字母。所以如果输入的是小写字母,程序会发出垃圾值。

+0

感谢您的帮助。我工作了! – 2014-11-03 10:59:13

+0

是的,我正在为大写字母编写此代码。 – 2014-11-03 11:05:19

0

只是零初始化输出缓冲器,它会工作(;替换此:

char message[200], en_message[200]; 

与此:

char message[200] = {0}, en_message[200] = {0}; 
+0

非常感谢您的帮助 – 2014-11-03 11:00:08

+0

或'= {};'就够了。 – 2014-11-05 14:55:49