14.逻辑行计数

高老师发明了一种新的语言来开发程序,这个语言的特点如下:

有两种形式的字符串,一种为加单引号,另一种加双引号。单引号的字符串可以包含双引号,双引号的字符串也可以包含单引号。字符串不能分行,其中也不能包含同样的引号字符。
有两种注释方式:@字符为行注释,而双括号(())内的文本为块注释。
块注释不能嵌套,所有在块中的文本均被忽略。一个块可以包含几行文本。
注释不能出现在字符串内。
在块注释中的行注释字符和引号都是没有意义的。
注释行中的双括号和引号都是没有意义的。
程序的任何部分都不能出现“#”字符;即使在字符串或注释内。
分号用来终止语句和生命。每个不在注释或字符串中的分号都被作为程序逻辑行的结束。
可以用逻辑行数来粗略地评估程序的大小,即计算不在注释或字符串内的分号的个数。写一个程序读进去几组程序代码,对每组代码都输出逻辑行数和物理行数,并对未终止的注释块和字符串发出警告消息。

输入

输入包含一个或多个程序,以#表示每个程序终止,以##表示输入终止。

输出

对于包括未终止字符串的行,输出:“Unterminated string in line n.”,其中n换成行号。

如果该程序包括一个未终止的块注释,以如下格式输出一行:”Unterminated block comment at end of program.“

在错误信息之后,以如下格式输出一行:”Program x contains y logical lines and z physical lines.“。其中x、y和z用相应的数字代替。

测试用例
in:
((Block comment:))
“string” ; (‘another string;’);@line comment

out:
Program 1 contains 2 logical lines and 2 physical lines.

模拟题目意思就行,由于题目没有数量范围,所以读入字符。

#include<stdio.h>
#include<string.h>
char ch1,ch2;
int count=1,physics=0,logical=0;
int isBlockComment=0,isRowComment=0,isEnd=0,isSingle=0,isDouble=0;
int main()
{
	while((ch1=getchar())!=EOF)
	{
		if(isEnd)
			break;
		judge:
		{
			if(ch1=='(')
			{
				ch2=getchar();
				if(ch2=='('&&!isRowComment&&!isBlockComment)
					isBlockComment=1;
				else
				{
					ch1=ch2;
					goto judge;
				}
			}
			else if(ch1==')')
			{
				ch2=getchar();
				if(ch2==')'&&!isRowComment&&isBlockComment)
					isBlockComment=0;
				else
				{
					ch1=ch2;
					goto judge;
				}
			}
			else if(ch1=='@')
			{
				if(!isBlockComment)
					isRowComment=1;
			}
			else if(ch1=='\'')
			{
				if(!isBlockComment&&!isRowComment&&!isDouble)
					isSingle^=1;
			}
			else if(ch1=='\"')
			{
				if(!isBlockComment&&!isRowComment&&!isSingle)
					isDouble^=1;
			}
			else if(ch1==';')
			{
				if(!isBlockComment&&!isRowComment&&!isSingle&&!isDouble)
					logical++;
			}
			else if(ch1=='\n')
			{
				physics++;
				if(isRowComment)
					isRowComment=0;
				if(isSingle||isDouble)
				{
					printf("Unterminated string in line %d.\n", physics);
					isSingle=isDouble=0;
				}
			}
			else if(ch1=='#')
			{
				if(isSingle||isDouble)
				{
					printf("Unterminated string in line %d.\n",physics);
					isSingle=isDouble=0;
				}
				if(isBlockComment)
					puts("Unterminated block comment at end of program.");
				printf("Program %d contains %d logical lines and %d physical lines.\n",count,logical,physics);
				count++;
				physics=logical=0;
				isDouble=isSingle=isBlockComment=isRowComment=0;
				ch2=getchar();
				if(ch2=='#')
					isEnd=1;
				else if(ch2!='\n')
				{
					ch1=ch2;
					goto judge;
				}
			}
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/ArgentumHook/article/details/83054681