http://acm.sgu.ru/problem.php?contest=0&problem=340

将tex格式转为HTML格式,这道题主要就是考逻辑清不清晰还有栈的应用.

#include <cstdio>
#include 
<stack>
#include 
<cctype>

using namespace std;

int main(void) {
    
char ch;
    stack
<char> sym;
    
while ((ch = getchar()) != EOF) {
        
while ((ch = getchar()) != '$') {
            
if (ch == ' ') {
                
continue;
            }
            
if (isalpha(ch)) {
                
if (sym.empty() || sym.top() == '{') {
                    printf (
"<i>%c", ch);
                    sym.push(
'c');
                } 
else if (sym.top() == '^' || sym.top() == '_'){
                    printf (
"<i>%c</i>%s", ch, (sym.top() == '^'? "</sup>" : "</sub>");
                    sym.pop();
                } 
else {
                    putchar(ch);
                }
            } 
else {
                
if (!sym.empty() && sym.top() == 'c') {
                    printf (
"</i>");
                    sym.pop();
                }
                
if (ch == '^' || ch == '_') {
                    sym.push(ch);
                    printf (
"%s", ch == '^' ? "<sup>" : "<sub>");
                } 
else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
                    printf (
"&nbsp;%c&nbsp;", ch);
                } 
else if (ch == '{') {
                    sym.push(
'{');
                } 
else if (ch == '}') {
                    sym.pop();
                    printf (
"%s", sym.top() == '^' ? "</sup>" : "</sub>");
                    sym.pop();
                } 
else if (isdigit(ch)) {
                    putchar(ch);
                    
if (!sym.empty() && (sym.top() == '^' || sym.top() == '_')) {
                        printf (
"%s", (sym.top() == '^'? "</sup>" : "</sub>");
                        sym.pop();
                    }
                } 
else {
                    putchar(ch);
                }
            }
        }
        
if (!sym.empty()) {
            printf (
"</i>");
            sym.pop();
        }
        putchar(
'\n');
        getchar();
    }
    
return 0;
}


posted on 2010-05-19 17:12 Willing 阅读(341) 评论(0)  编辑 收藏 引用 所属分类: ACM

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理