C编写chck正确性 [英] C prog to chck correctness

查看:88
本文介绍了C编写chck正确性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何制作一个C程序来检查另一个程序的正确性,仅限于打开和关闭'{','(','['。



我尝试了什么:



i猜需要使用堆栈?不知道相同。

How to make a C program that checks the correctness of another program, limited to opening and closing of '{', '(', '[' .

What I have tried:

i guess need to use stack ? getting no idea of the same.

推荐答案

最简单的方法是创建自己的堆栈并解析数据。你的堆栈只是一个数组和一个索引,上面写着下一个免费位置

看看每个字符从数据中删除,并且:

如果它是一个左括号,将它添加到堆栈然后递增索引。

如果它是一个结束括号,删除堆栈顶部的项目(通过减少索引并查看其上的项目)并检查它是否为相同类型:'('for')','{'for'}'等等。

否则,忽略它。

当你到达数据的末尾时,如果索引为零,那么输入中的任何括号都匹配。



高级版本可能允许C字符串中的括号和字符定义
The simplest way is to create your own stack, and parse the data. Your stack is simply an array and an index which says "next free location"
Look at each character as you remove it from the data, and:
If it is a opening bracket, add it to your stack then increment the index.
If it's a closing bracket, remove the item at the top of the stack (by reducing the index and looking at the item on it) and check it's the same type: '(' for ')', '{' for '}' and so on.
Otherwise, ignore it.
When you get to the end of the data, if the index is zero, then any brackets in the input match up.

The advanced version might allow for brackets within C strings and character definitions
"The close bracket character is ')' while the open bracket is '('."

。我不知道你的作业是否需要这样做!

for example. I don't know if that is required for your homework though!


如果您不必关心预处理器或评论,那么工作就相当容易了。打开括号,括号或括号只是查找字符的出现。关闭其中一个基本相同,虽然使用不同的角色,但必须首先打开它。如果没有,那么它是不正确的。此外,在文件末尾打开的任何文件也是不正确的。在真正的解析器中,是的,堆栈将用于此,但为了您的目的,它可以更简单。你需要的只是柜台三个柜台。在零处开始计数器,在找到开始字符时递增,并在找到相应的结束字符时递减计数器。首先在文本模式下打开文件,fopen可以这样做。然后一次读取单个字符并如上所述评估每个字符。函数fread可以做到这一点。记得在到达文件末尾时调用fclose。
If you don't have to care about the pre-processor or comments then the job is rather easy. Opening a brace, parenthesis, or bracket is just looking for the occurrence of the character. Closing one of them is essentially the same, although using a different character, with the caveat that it must be open first. If not then it is incorrect. Also, any of those left open at the end of the file are incorrect also. In a real parser, yes, a stack would be used for this but for your purpose it can be much simpler. All you need are counters three counters. Start the counters at zero, increment when an opening character is found, and decrement them when the corresponding closing character is found. Start by opening the file in text mode, fopen can do this. Then read single characters at a time and evaluate each one as noted above. The function fread can do this. Remember to call fclose when the end of the file is reached.


您可以使用带有类型信息的新元素的链表来永久打开元素,并为每个结束元素删除它。双链表应该更好。
You can use a linked list with a new element with type information for ever opening element and removing it for every closing element. A double linked list should be better.


这篇关于C编写chck正确性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆