C/C++ 学习笔记[03].去掉C风格的注释
网上搜索了一大堆去掉/*和*/之间注释的代码,就像<The C Programming Language>练习1-23里有人说的一样
大部分都会被以下的程序broken,这个功能看起来简单,实际上很有难度.网上实现的代码,除了我找到的一个用文件指针实现的没有问题外,其余的都存在各种bug,不信的话就用以下的程序测试一下:-),当然这个程序也不够完善.
还是有限状态自动机实现起来更严谨也容易理解得多:
/* krx123tp.c - a test program to serve as input to krx123*.c
*
* This is a shameless copy of Ben Pfaff's solution, to which I have
* added a few extra statements to further test the candidate programs
* for this exercise. As Ben says, this program already contains lots
* of examples of comments and not-quite-comments. I've just made it
* a little tougher.
*
*/
/* K&R2 1-23: Write a program to remove all comments from a C program.
Don't forget to handle quoted strings and character constants
properly. C comments do not nest.
This solution does not deal with other special cases, such as
trigraphs, line continuation with \, or <> quoting on #include,
since these aren't mentioned up 'til then in K&R2. Perhaps this is
cheating.
Note that this program contains both comments and quoted strings of
text that looks like comments, so running it on itself is a
reasonable test. It also contains examples of a comment that ends
in a star and a comment preceded by a slash. Note that the latter
will break C99 compilers and C89 compilers with // comment
extensions.
Interface: The C source file is read from stdin and the
comment-less output is written to stdout. **/
#include <stdio.h>
int
main(void)
{
/* State machine's current state. */
enum {
PROGRAM,
SLASH,
COMMENT,
STAR,
QUOTE,
LITERAL
} state;
/* If state == QUOTE, then ' or ". Otherwise, undefined. */
int quote;
state = PROGRAM;
for (;;) {
int c = getchar();
if (c == EOF)
相关文档:
#include <stdio.h>
#include <string.h>
int
main(void)
{
char str[] =
"3BVPSq4xF.K?=u#,"
"G'K<MrDnRr7gH%#,"
"XKf<f%G`w^=?C<#,"
"HgU_AnNR?*PDQU#,"
......
联系1-9编写一个将输入复制到输出的程序,并将其中连续的多个空格用一个空格代替。
#include "stdio.h"
main(){
int c;
int flag;
flag=0;//是否空格标志
while ((c=getchar())!=EOF){
if (c!=32) {
putchar(c);
flag=0;
}else if(flag==0){
flag=1;
putchar(c);
}
/* ......
c库函数详解——assert
函数名: assert
功 能: 测试一个条件并可能使程序终止
用 法: void assert(int test);
程序例:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
struct ITEM {
int key;
int value;
};
/* add item to ......
今天看K&R的书的时候顺便温习了C的另一重要数据结构bit-fields,我想bit-fields在编写底层驱动
驱动程序的时候应该比较好用,它可以绕开"&"和"|"进行位操作,而且更加节约内存空间。废话不多说
了,还是先来看看它的真面目吧:
bit-field来源:
bit-field是为了节约存储空间而创造的一种数� ......
与 &: 任何位用&运算与0结合结果为0,与1结合结果为其本身;
或 | : 任何位用|运算与0结合结果为其本身,与1结合结果为1;
异或 ^ : 任何位用^运算与0结合结果为其本身,与1结合则取反; ......