2014-02-10 89 views
-1

我试图写一个C++程序创建的,将 被用来根据下列规则对消息进行编码的字母列表:堆栈腐败

  1. 输入一个字
  2. 删除所有重复的字母形成改性字
  3. 将在阵列
  4. 开头的修饰词填充从一个工作到没有这个词使用的字母表中的任何字母列表的其余部分Z.(你的名单应该是哈已经字母表的所有26个字母)

例如,如果用户输入HELLO,修改后的一句话都成为HELO和列表将成为HELOABCDFGIJKMNPQRSTUVXYZ。该列表必须存储在CHARACTER数组中。

这是我写的代码:

#include <iostream> 
using namespace std; 
int main() 
{ 
    char a; 
    int b = 0; 
    char word[4] = "\0"; 
    char alphabet[27] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
    char code[27]; 
    cout << "Please enter a word:" << endl; 
    cin >> word; 
    for (int i = 0; i<3; i++) 
    { 
     if (word[i] == word[i - 1]) 
     { 
      a = word[i]; 
      word[i] = word[i + 1]; 
     } 
     code[i] = word[i]; 
     b++; 
    } 
    for (int o = 0; o<27; o++) 
    { 
     if (alphabet[o] == word[1] || alphabet[o] == word[2] || alphabet[o] == word[3] || alphabet[o] == word[0]) 
     { 
      o++; 
     } 
     code[b] = alphabet[o]; 
     b++; 
    } 
    cout << code; 
    return 0; 
} 

不幸的是,我得到这个错误:

Run-Time Check Failure #2
Stack around the variable word was corrupted.

其次,我的代码适用于4个字符。我怎样才能让它适用于任何单词?

+1

“我不知道什么是错我的代码” - 你应该介绍一些输入,它失败了,什么导致它产生你所期望的东西,你在哪里陷入困惑,为什么......这个网站不适用于一般的代码审查 - 我们需要一个特定的问题。 (我希望你认识到这是一个积极的评论,鼓励你正确地设置你的问题,以便人们可以并且会帮助你)。 –

+0

是的我的错。首先,我得到这个错误 - 运行时检查失败#2 - 围绕变量“字”的堆栈已损坏。第二我的代码适用于4个字符我如何使它适用于任何单词?谢谢 – user3035168

+0

'if(word [i] == word [i - 1]) - 当第一次迭代时i == 0时会发生什么? – ChiefTwoPencils

回答

1

这是一个简单的方法来做这个任务。 注意,输入字lenght应小于100

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main() 
{ 
    char word[100]; // input word lenght should be smaller than 100 
    char used[26]; 
    memset(used, 0, 26); 
    scanf("%s", word); 

    for (int i=0; i<strlen(word); i++) 
    { 
     // convert to uppercase 
     if (word[i]>='a' && word[i]<='z') 
      word[i] -= 'a'-'A'; 

     // skip non-alphabetic characters 
     if (word[i]<'A' || word[i]>'Z') 
      continue; 

     // print this char only if it's not been printed before 
     if (!used[word[i]-'A']) 
      printf("%c", word[i]); 

     // set to 1 so that we don't print it again 
     used[word[i]-'A'] = 1; 
    } 

    // print all unused characters 
    for (int i=0; i<26; i++) 
     if (!used[i]) 
      printf("%c", i+'A'); 
    printf("\n"); 
    return 0; 
}