插入阵列的额外字符

时间:2013-09-03 00:29:02

标签: c++ arrays anagram

我是一名C ++初学者并编写了一个程序来检查两个短语是否是字谜。正在一次读取一个字符并将其存储在一个数组中。我有一切工作,除了在某些情况下,额外的字符被插入数组。

例如,如果我输入短语aabb和abba,这就是程序的输出:

输入可能是字谜的两行:
- > AABB
- > ABBA
字符串A是aabb
字符串B是abbai?
这两个字符串不是字谜。

他们应该是字谜,但出于某种原因,我呢?被添加到数组中,导致短语不是字谜。我可能忽略了代码中的一个简单错误,但非常感谢任何反馈。

以下是代码:

#include <string>
#include <algorithm>
#include <iostream>
using namespace std;

int check_anagram(char [], char []);

int main()
{
    char ch, a[60], b[60];
    int flag, i;

    cout << "Enter two lines that might be anagrams:" << endl;
    cout << "--> ";

    cin.get(ch);
    ch = tolower(ch);

    i = 0;
    while (ch != '\n')
    {
        if (ch > '@') {
            a[i] = ch;
            i++;
        }
        cin.get(ch);
        ch = tolower(ch);
    }

    cout << "--> ";

    cin.get(ch);
    ch = tolower(ch);

    i = 0;
    while (ch != '\n')
    {
        if (ch > '@') {
            b[i] = ch;
                i++;
        }
        cin.get(ch);
        ch = tolower(ch);
    }

    flag = check_anagram(a, b);

    cout << "String A is " << a << endl;
    cout << "String B is " << b << endl;

    cout << "The two strings ";
    if (flag == 1)
        cout << "ARE";
    else
        cout << "are NOT";
    cout << " anagrams." << endl << endl;

    return 0;
}

int check_anagram(char a[], char b[])
{
    int first[26] = {0}, second[26] = {0}, c = 0;

    while (a[c] != '\0')
    {
        first[a[c]-'a']++;
        c++;
    }

    c = 0;

    while (b[c] != '\0')
    {
        second[b[c]-'a']++;
        c++;
    }

    for (c = 0; c < 26; c++)
    {
        if (first[c] != second[c])
            return 0;
    }

    return 1;
}

提前致谢!

1 个答案:

答案 0 :(得分:3)

您只需要使用'\0'终止两个字符数组,因为check_anagram中的逻辑将两个数组视为以NULL结尾。

   ..
   while (ch != '\n')
   {
      if (ch > '@') {
         a[i] = ch;
         i++;
      }
      cin.get(ch);
      ch = tolower(ch);
   }

   a[i] = '\0';     // <<<<<<<< Add this line
   cout << "--> ";

   cin.get(ch);
   ch = tolower(ch);

   i = 0;
   while (ch != '\n')
   {
      if (ch > '@') {
         b[i] = ch;
         i++;
      }
      cin.get(ch);
      ch = tolower(ch);
   }

   b[i] = '\0';     // <<<<<<<< Add this line
   ..

结果如下:

Enter two lines that might be anagrams:
--> aabb
--> abba
String A is aabb
String B is abba
The two strings ARE anagrams.