0

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

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

输入可能是字谜的两行:
--> aabb
--> abba
String A is aabb
String B is 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;
}

提前致谢!

4

1 回答 1

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.
于 2013-09-03T00:37:46.293 回答