题意:给出你HTML的格式标记,让你按照层次,把对应的格式输出出来。
思路:因为整个层次可以看做是个递归的,我们就可以递归来写。
其中需要非常注意的是,会有个空括号,他是不会让层次加1的。
同时,在C++中,cin会自动的跳过空格字符,如果想一个字符一个字符的读,要用cin.get().
整体结构还是挺清晰的,看代码吧。
代码如下:
#include <string>
#include <iostream>
#include <cctype>
#include <cstdio>
using namespace std;
void space(int d)
{
for(int i = 0; i < d; ++i)
cout<<' ';
}
void gettag(string& tag)
{
tag.clear();
char ch;
ch = cin.get();
while(ch != '>'){
tag += ch;
ch = cin.get();
}
}
void word()
{
char ch;
ch = cin.get();
bool sig = true;
while(ch != '<'){
if(sig) sig = false;
else cout<<' ';
do{
cout<<ch;
ch = cin.get();
}while(!isspace(ch) && ch != '<');
if(isspace(ch)){
while(isspace(ch))
ch = cin.get();
}
}
cin.putback(ch);
cout<<'\n';
}
void solve(int d,string tag,bool sig)
{
char ch;
string tag2;
if(sig){
space(d);
if(tag.size() == 0)
word();//输出单词
else
cout<<"<"<<tag<<">\n";//输出空括号
}
else{
space(d); cout<<"<"<<tag<<">\n";
while(true){
cin>>ch;
if(ch != '<'){
cin.putback(ch);
solve(d+1,"",true);
}
else{
gettag(tag2);
if(tag2[tag2.size()-1] == '/')
solve(d+1,tag2,true);//为空括号
else if(tag2[0] == '/')//为结束括号
break;
else//否则为开始括号
solve(d+1,tag2,false);
}
}
//输出结束括号,要把class内容删掉
int pos = tag.find(' ');
if(pos != -1)
tag.erase(pos);
space(d);cout<<"</"<<tag<<">\n";
}
}
int main(void)
{
//freopen("input.txt","r",stdin);
//freopen("out.txt","w",stdout);
ios::sync_with_stdio(false);
int T;
cin>>T;
char ch;
for(int i = 1; i <= T; ++i){
cout<<"Case #"<<i<<":\n";
string tag;
cin>>ch;
gettag(tag);
solve(0,tag,false);
//cout<<tag<<endl;
}
return 0;
}