我正在尝试编写一个C ++程序来创建一个字母列表 用于根据以下规则对消息进行编码:
例如,如果用户输入HELLO
,则修改后的字词将变为HELO
,列表将变为HELOABCDFGIJKMNPQRSTUVXYZ
。该列表必须存储在CHARacters数组中。
这是我写的代码:
#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;
}
不幸的是,我收到了这个错误:
运行时检查失败#2
变量word
周围的堆栈已损坏。
其次,我的代码适用于4个字符。我怎样才能让它适用于任何单词?
答案 0 :(得分:1)
这是执行此任务的简单方法。 请注意,输入字长应小于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;
}