4

これは正常にコンパイルされ、スペースがなくてもうまく機能しますが、スペースを入れると、回文ではないと表示されるか、タイムアウトになります。どんな助けでも大歓迎です!

int main( )
{
   queue<char> q;
   stack<char> s;
   string the_string;
   int mismatches = 0;
   cout << "Enter a line and I will see if it's a palindrome:" << endl;
   cin  >> the_string;

   int i = 0;
   while (cin.peek() != '\n')
   {
       cin >> the_string[i];
       if (isalpha(the_string[i]))
       {
          q.push(toupper(the_string[i]));
          s.push(toupper(the_string[i]));
       }
       i++;
   }

   while ((!q.empty()) && (!s.empty()))
   {
      if (q.front() != s.top())
          ++mismatches;

        q.pop();
        s.pop();
   }

   if (mismatches == 0)
       cout << "This is a palindrome" << endl;
   else
       cout << "This is not a palindrome" << endl;

   system("pause");
   return EXIT_SUCCESS;
}
4

4 に答える 4

1

まずはライン

cin >> the_string;

行全体を取得しません。代わりにこれを使用してください

getline(cin, the_string);

次に、アルゴリズムのデバッグ中に多くの情報を出力します。たとえば、次の行を追加すると

cout << "You entered: '" << the_string << "'" << endl;

実際にテストしている文字列を簡単に確認できます。

于 2013-03-24T04:46:20.890 に答える
1

私はこのソリューションをうまく機能させました。

int main( )
{
    queue<char> q;
    stack<char> s;
    string the_string;
    int mismatches = 0;

    cout << "Enter a line and I will see if it's a palindrome:" << endl;
    int i = 0;

    while (cin.peek() != '\n')
    {
        cin >> the_string[i];
        if (isalpha(the_string[i]))
        {
            q.push(toupper(the_string[i]));
            s.push(toupper(the_string[i]));
    }
    i++;
    }

    while ((!q.empty()) && (!s.empty()))
    {
        if (q.front() != s.top())
            ++mismatches;

        q.pop();
        s.pop();
    }

if (mismatches == 0)
    cout << "This is a palindrome" << endl;
else
    cout << "This is not a palindrome" << endl;

    system("pause");
    return EXIT_SUCCESS;
}
于 2013-03-24T06:16:33.013 に答える
1

なぜそんなに複雑なのですか?

あなたは単に行うことができます:

#include <string>
#include <algorithm>

bool is_palindrome(std::string const& s)
{
  return std::equal(s.begin(), s.begin()+s.length()/2, s.rbegin());
}
于 2013-03-24T04:35:51.593 に答える
-1
void main()
{
    queue<char> q;
    stack<char> s;
    char letter;
    int mismatches = 0;


    cout << "Enter a word and I will see if it's a palindrome:" << endl;
    cin >> letter;
    q.push(letter);
    s.push(letter);

    int i = 0;
    while (cin.peek() != '\n')
    {
        cin >> letter;
        if (isalpha(letter))
        {
            q.push(letter);
            s.push(letter);
        }
        i++;
    }

    while ((!q.empty()) && (!s.empty()))
    {
        if (q.front() != s.top())
            ++mismatches;

        q.pop();
        s.pop();
    }

    if (mismatches == 0)
    {
        cout << "This is a palindrome" << endl;
    }
    else
    {
        cout << "This is not a palindrome" << endl;
    }
    cout << endl;
    cout << "Homework done!" << endl;
    cout << "You are Welcome!" << endl;
    system("pause");

}
于 2015-11-12T03:11:06.450 に答える