逐字逐句程序

时间:2013-03-25 04:52:19

标签: c++ queue stack

因此,我发现了一百万个回文程序示例,用于检查单个回文词。

但是T需要帮助一个字一个字地做一个例如句子你可以笼住燕子你不能但是你不能吞下一个笼子吗?“这将是一个单词palindrome。我只需要一个跳转启动示例代码这本书给的是这个

// 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;    

}

1 个答案:

答案 0 :(得分: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);

将字符串中的所有字符转换为大写。