C程式語言(第2版) 課後練習題4 10

2021-10-19 05:25:42 字數 3031 閱讀 3396

練習4-10 另一種方法是通過getline函式讀入整個輸入行,這種情況下可以不使用getch與ungetch函式。請運用這一方法修改電腦程式。

#include

#include

#include

#include

#include

#include

#define number '0'

#define function '1'

#define maxlen 100

#define maxop 100

#define maxval 100

int sp =0;

//next free position in val;

double val[maxval]

;int

getop

(char to,

char in,

int* inp)

;void

push

(double f)

;double

pop(

void);

//int getch(void);

//void ungetch(int c);

void

dealwithname

(char s)

;int

getline

(char s,

int maxlen)

;void

showtop

(void);

//#void

duplicate

(void);

//$void

swapitems

(void);

//?void

clearstack

(void);

//!main()

else

printf

("error: zero divisor\n");

break

;case

'#':

showtop()

;break

;case

'$':

duplicate()

;break

;case

'?':

swapitems()

;break

;case

'!':

clearstack()

;break

;case

'\n'

:printf

("\t%.8g\n"

,pop()

);break

;default

:printf

("error:unknown command %s\n"

, to)

;break;}

}}return0;

}//這是採用getline的方案

intgetline

(char s,

int maxlen)

intgetop

(char to,

char in,

int* inp)if(

!isdigit

(c)&& c !=

'-')

if(c ==

'-')

else}if

(isdigit

(c))

while

(isdigit

(to[

++i]

= c = in[

(*inp)++]

));if

(c ==

'.')

while

(isdigit

(to[

++i]

= c = in[

(*inp)++]

)); to[i]

='\0';if

(c !=

eof)--(

*inp)

;return number;

}#define maxval 100

int sp =0;

//next free position in val;

double val[maxval]

;void

push

(double f)

double

pop()}

void

showtop

(void

)void

duplicate

(void

)void

swapitems

(void)}

void

clearstack

(void

)//這是採用getch與ungetch的方案

/*int getop(char s)

if (!isdigit(c) && c != '-')

return c;

if (c == '-')

else

} if (isdigit(c))

while (isdigit(s[++i] = c = getch()))

;if (c == '.')

while (isdigit(s[++i] = c = getch()))

;s[i] = '\0';

if (c != eof)

ungetch(c);

return number;

}#define bufsize 100

int buf[bufsize];

int bufp = 0; //next free position in buf;

int getch(void)

void ungetch(int c) */

void

dealwithname

(char s)

else

printf

("%s is not a supported function.\n"

, s)

;}

C程式語言(第2版) 課後練習題1 13

練習1 13 編寫乙個程式,列印輸入中單詞長度的直方圖。水平方向的直方圖比較容易繪製,垂直方向的直方圖則要困難些。橫向向列印輸入中單詞長度的直方圖 include define maxwordnum 100 最大單詞數 main clast cnow 橫向直方圖繪製 for i 0 i 縱向列印輸入...

C程式語言(第2版) 課後練習題1 18

練習1 18 編寫乙個程式,編寫乙個程式,刪除每個輸入行末尾的空格及製表符,並刪除完全是空格的行 include define maxlen 1000 輸入文字的最大字元量 intgetline char s,int maxlen 將當前鍵盤輸入的句子儲存到字元陣列中,並返回每次輸入句子長度 包含換...

C程式語言(第2版) 課後練習題5 13

練習5 13 編寫程式tail,將其輸入中的最後n行列印出來。預設情況下,n的值為10,但可通過乙個可選引數改變n的值,因此,命令 tail n 將列印其輸入的最後n行。無論輸入或n的值是否合理,該程式都應該能正常執行。編寫程式時要充分利用儲存空間 輸入行的儲存方式應該同5.6節中排序程式的儲存方式...