【问题标题】:Extra Characters Inserted Into Array插入数组的额外字符
【发布时间】:2013-09-06 02:31:29
【问题描述】:

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

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

输入两行可能是字谜的:
--> aabb
--> 阿爸
字符串 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;
}

提前致谢!

【问题讨论】:

    标签: c++ arrays anagram


    【解决方案1】:

    您只需要用'\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.
    

    【讨论】:

    • 我知道这很简单。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 2014-04-18
    • 1970-01-01
    • 2012-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多