2014-02-10 87 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; 
}