C复习笔记(3)-6.19
来源:互联网 发布:网络公益众筹 编辑:程序博客网 时间:2024/05/16 19:00
6月19日.
(1)
Write a program to count blanks, tabs, and newlines.
#include <stdio.h>
int main(void)
{
int blanks, tabs, newlines;
int c;
int done = 0;
int lastchar = 0;
blanks = 0;
tabs = 0;
newlines = 0;
while(done == 0)
{
c = getchar();
if(c == ' ')
++blanks;
if(c == '/t')
++tabs;
if(c == '/n')
++newlines;
if(c == EOF)
{
if(lastchar != '/n')
{
++newlines; /* this is a bit of a semantic stretch, but it copes
* with implementations where a text file might not
* end with a newline.
*/
}
done = 1;
}
lastchar = c;
}
printf("Blanks: %d/nTabs: %d/nLines: %d/n", blanks, tabs, newlines);
return 0;
}
Note: if all the inputs are from keyboard, then every line ended with a newline.
(2)
Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.
Besides the answer in the C Answer Book, I uses the Continue Statement.
#include <stdio.h>
int main(void)
{
int c;
int lastchar;
while ((c = getchar())!= EOF)
{
if (c == ' ')
{
if (lastchar == ' ')
continue;
}
putchar(c);
lastchar = c;
}
}
(3)
Write a program to copy its input to its output, replacing each tab by /t
, each backspace by /b
, and each backslash by //
. This makes tabs and backspaces visible in an unambiguous way.
#include <stdio.h>
int main(void)
{
int c;
while ((c = getchar())!= EOF)
{
if (c == '/b')
{
printf("//b");
continue;
}
if (c == '/t')
{
printf("//t");
continue;
}
if (c == '//')
{
printf("////");
continue;
}
putchar(c);
}
}
Why I copy the code here? I don’t know how to input a Backspace from keyboard.
#include <stdio.h>
#define IN 1 /*inside a word*/
#define OUT 0 /*outside a word*/
/*word counting*/
int main()
{
int c;
int state = OUT;
int count = 0;
while ((c=getchar()) != EOF) {
if ((c != ' ') && (c != '/t') && (c != '/n'))
{
if(state == OUT)
++count;
state = IN;
}
else
{
state = OUT;
}
}
printf("%d",count);
return 0;
}
You'll also find that it's easier to make extensive changes in programs where magic numbers appear only as symbolic constants.
Expressions connected by && or || are evaluated left to right, and it is guaranteed that evaluation will stop as soon as the truth or falsehood is known.
static char *str = "a b c d e f g h i j k l m "
"a b c d e f g h i j k l m "
"n/n";
The string can be defined like this, have you seen this before, aha!
- C复习笔记(3)-6.19
- C语言复习笔记 3
- c复习笔记
- C语言复习笔记
- C语言复习笔记
- C笔记复习
- C--复习笔记
- C & C++ 复习笔记
- C复习笔记(1)-6.16
- C复习笔记(2)-6.18
- C复习笔记(4)-6.20
- C复习笔记(5)-6.23
- C复习笔记(6)-6.24
- C复习笔记(7)-7.4
- C复习笔记(7)-7.4
- c语言复习笔记1
- C语言老师复习笔记
- C语言复习笔记 1
- Using Data and Variables
- 1104工程
- Mscomm设置
- 查看内存C++
- struts标记库
- C复习笔记(3)-6.19
- GPRS 彩信发送
- 上海--怡情的雨
- 编程思想爱情版
- 向狼学习十条处世哲学
- 网页显示的几种常用字体
- 学习 10 种良好的 XML 使用习惯
- Microsoft Enterprise Lib 系列文章
- 来点有用的