0

そのため、Tは、1語の回文をチェックする回文プログラムの例を100万個見つけました。

しかし、Tは単語ごとに助けが必要です。たとえば、「ツバメをケージに入れることはできますが、ケージを飲み込むことはできませんか?」という文は、単語ごとに回文になります。これは

// FILE: pal.cxx
// Program to test whether an input line is a palindrome. Spaces,
// punctuation, and the difference between upper- and lowercase are ignored.

#include <cassert>    // Provides assert
#include <cctype>     // Provides isalpha, toupper
#include <cstdlib>    // Provides EXIT_SUCCESS
#include <iostream>   // Provides cout, cin, peek
#include <queue>      // Provides the queue template class
#include <stack>      // Provides the stack template class
using namespace std;

int main( )
{
queue<char> q;
stack<char> s;
char letter;            
queue<char>::size_type mismatches = 0;  // Mismatches between queue and stack
cout << "Enter a line and I will see if it's a palindrome:" << endl;

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

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

if (mismatches == 0)
    cout << "That is a palindrome." << endl;
else
    cout << "That is not a palindrome." << endl;    
return EXIT_SUCCESS;    

}

4

1 に答える 1

1

これは、実際にはベースコードから非常に簡単に実行できます。文字の代わりに単語(文字列)をキューとスタックに追加するだけです。私はすぐにコードを変更しました:

#include <algorithm>
queue<std::string> q;
stack<std::string> s;
std::string word;
queue<std::string>::size_type mismatches = 0;  // Mismatches between queue and stack
cout << "Enter a line and I will see if it's a palindrome:" << endl;

while (cin.peek( ) != '\n')
{
    cin >> word;
    std::transform(word.begin(), word.end(), word.begin(), ::toupper);
    q.push(word);
    s.push(word);
}

cinを使用して文字列を読み取ると、区切り文字として空白が自動的に使用されます。この線:

std::transform(word.begin(), word.end(),word.begin(), ::toupper);

文字列内のすべての文字を大文字に変換します。

于 2013-03-25T05:01:53.577 に答える