C語言授課記錄(一)
- 導語
- 輸入函式
- 回圈陳述句
- switch
- 陣列
- 字串初探
- qsort
- 字串相關函式
- 總結
導語
本次授課內容如下輸入函式(scanf/getchar/gets)、回圈陳述句(for、do while、while、break)、switch、陣列、字串初探
有時間則講解qsort、字串相關函式
輔助教材為《C語言程式設計現代方法》
輸入函式
scanf/printf在上次課程中已經進行了詳盡的講解,本次課程只著重于scanf/getchar與空白字符間的愛恨情仇
輸入輸出原理簡介
程式的輸入建有一個緩沖區,即輸入緩沖區,當一次鍵盤輸入結束時會將輸入的資料存入輸入緩沖區,函式從緩沖區中取出資料,此時資料在緩沖區中消失,讀取時遇到‘\n’結束,’\n’會進入輸入流緩沖區,接受輸入時取走字符后會留下‘\n’,第二次的讀入函式從緩沖區中把’\n’取走
實體代碼1
#include <stdio.h>
#include <stdlib.h>
int main()
{
char a,b;
//scanf("%c",&a);
//scanf("%c",&b);
scanf("%c%c",&a,&b);
return 0;
}
進行debug跟蹤后會發現,b并未錄入預期的第二個字符,而是錄入了空格
實體代碼2
#include <stdio.h>
#include <stdlib.h>
int main()
{
char b;
int a;
scanf("%d",&a);
b=getchar();
return 0;
}
進行debug跟蹤后會發現,b錄入了’\n’,a錄入數值,如果一開始一直輸入空白字符,則a不會錄入(思考一下為什么)
實體代碼3
#include <stdio.h>
#include <stdlib.h>
int main()
{
char b;
char a;
scanf(" %c",&a);
scanf(" %c",&b);
return 0;
}
進行debug跟蹤后會發現,一直輸入空白字符,a與b均無法掃入
關于gets
以下為API中對gets的講解

教材P204(左上)
總結
在使用scanf/getchar函式時要注意緩沖區的存在,時常思考’\n’是否在緩沖區中,如果’\n’在緩沖區中,需要進行相應的處理,例如再加上一個getchar將’\n’從緩沖區讀出或者使用fflush函式清慷訓沖區
不要養成用gets的習慣,最好不要使用它
回圈陳述句
for
以下為API中對for的講解

教材P74(左上)
逗號運算子
教材P76(左上)
while
以下為API中對while講解

教材P99(右上)
do-while
以下為API中對do-while講解

教材P72(左上)
break
以下為API中對break講解

教材P78(左上)
重點
do-while和while的區別
實體代碼4
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i=0;
do
{
i--;
}while(i>0);
printf("%d\n",i);
i=0;
while(i>0)
{
i--;
}
printf("%d\n",i);
return 0;
}
通過輸出可以看出do-while與while在邏輯上的主要區別:
do-while為先執行,再判斷,while為先判斷,后執行
當然,還有do-while比while多了條尾巴
switch
以下為API中對switch講解

教材P59(右上)
陣列
基本定義:含有多個相同型別資料值的資料結構,且邏輯地址與物理地址都為順序,
實體代碼5
#include <stdio.h>
#include <stdlib.h>
int main()
{
int A[5],i=0;
for(i=0; i<5; i++)
{
scanf("%d",&A[i]);
}
for(i=0; i<5; i++)
{
printf("%d ",A[i]);
}
return 0;
}
教材P113(右上)
下標、初始化、sizeof
切記:陣列下標是從0開始計數的
字串初探
字串,現階段可以認為即字符陣列,在各種語言當中,對字串的處理都有著各自匹配的方法,C語言亦是如此,字串是C語言處理的常用資料
實體代碼6
#include <stdio.h>
#include <stdlib.h>
int main()
{
char A[5];
int i=0;
for(i=0; i<5; i++)
{
scanf("%c",&A[i]);
}
for(i=0; i<5; i++)
{
printf("%c ",A[i]);
}
return 0;
}
初始化、’\0’、輸入輸出函式
qsort
以下為API中對switch講解

comp的強制型別轉換與回傳值
快速排序演算法請自行了解
字串相關函式
strcpy、strcat、strcmp
以下為API中對這三個函式的講解



總結
本次課程對scanf/getchar/gets三個常用函式與空白字符間的關系進行了解釋,初步介紹了陣列、字串的概念與使用,對字串函式以及qsort進行了拓展,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/200322.html
標籤:其他
上一篇:求助:應用程式間的編程?
