【心得】Ctrl+Z、\n、\0、eof的区别和用法
從scanf談起:
一:scanf的返回值:讀入的域的個(gè)數(shù)
int scanf( const char *format [, argument]... ); int _scanf_l( const char *format, locale_t locale [, argument]... ); int wscanf( const wchar_t *format [, argument]... ); int _wscanf_l( const wchar_t *format, locale_t locale [, argument]... );Return Value
Returns the number of fields successfully converted and assigned; the return value does not include fields that were read but not assigned. A return value of 0 indicates that no fields were assigned.
If format is a NULL pointer, the invalid parameter handler is invoked, as described in Parameter Validation. If execution is allowed to continue, these functions return EOF and set errno to EINVAL.
For information on these and other error codes, see _doserrno, errno, _sys_errlist, and _sys_nerr.
二、scanf對(duì)特殊符號(hào)的返回值
自然數(shù):符合輸入格式的數(shù)據(jù)的個(gè)數(shù)
-
0:不符合輸入格式的數(shù)據(jù)(如果Ctrl+Z和回車鍵之間有其他字符,則也返回0)
以"%d"為例:要求是十進(jìn)制整數(shù),如果輸入字符'r'、'e'、'\'等,就返回0,自然地,'\n''\0''eof'也返回0,這與他們本身的含義(比如換行符、終止符、文件結(jié)束符)并無(wú)關(guān)系 -1:Ctrl+Z(緊接著按下回車鍵)
三、輸入流中Ctrl+Z的含義
注:Windows系統(tǒng)中一般采用阻塞式檢查 Ctrl+Z、Unix/Linux系統(tǒng)下一般采用非阻塞式的檢查 Ctrl+D。本程序是在Windows系統(tǒng)下,因此使用阻塞式的 Ctrl+Z 來(lái)標(biāo)識(shí)流的結(jié)束。
阻塞式方式的特點(diǎn):
只有按下回車之后才有可能檢測(cè)在此之前是否有Ctrl+Z按下。
(按照輸入時(shí)間順序讀取輸入緩沖區(qū)的數(shù)據(jù))讀取到Ctrl+Z時(shí),如果后面有可讀的數(shù)據(jù),則不會(huì)理睬Ctrl+Z,也就是不認(rèn)為Ctrl+Z代表著流的末尾。(因?yàn)橛幸x的數(shù)據(jù),還不能認(rèn)為到了流的末尾)。
Ctrl+Z產(chǎn)生的不是一個(gè)普通的ASCII碼值,也就是說(shuō)它產(chǎn)生的不是一個(gè)字符,所以不會(huì)跟其它從鍵盤(pán)上輸入的字符一樣能夠存放在輸入緩沖區(qū)。
四、鍵盤(pán)輸入時(shí)回車鍵的作用:
將鍵盤(pán)上敲下的字符送入輸入緩沖區(qū)。
如果用戶在按回車鍵之前輸入了不只一個(gè)字符,其他字符會(huì)保留在鍵盤(pán)緩沖區(qū)中,等待后續(xù)的輸入函數(shù)(比如scanf()、getchar())調(diào)用讀取。也就是說(shuō),后續(xù)的scanf()調(diào)用不會(huì)等待用戶按鍵,而是直接讀取緩沖區(qū)中的字符,直到緩沖區(qū)的字符讀取完畢后,才等待用戶按鍵。
對(duì)于scanf(),只有字符char在輸入流中的獲取會(huì)承認(rèn)空格或回車中的換行符為所要取的值,別的如字符串或者字符數(shù)組或int類型均不認(rèn)為空格或回車中的換行符為其值即丟棄空格符和回車符,以空格作為劃分。
五、那換行符'\n'、終止符'\0'、文件結(jié)束符'eof'是干嘛的
'\n'、'\0'、'eof'是C/C++編譯器在編譯代碼時(shí)識(shí)別的符號(hào)。
Ctrl+Z是操作系統(tǒng)在處理輸入流時(shí)識(shí)別的符號(hào)。
'\n'換行符,
#include <stdio.h> int main() {int c;do{printf("請(qǐng)輸入文檔的結(jié)尾標(biāo)志");}while((c=getchar())!='\n');printf("已得到文檔結(jié)束標(biāo)志\n"); //直接回車return 0; }'\0'終止符
'\0' is the null termination character. It marks the end of the string.
is the same as
char cAlphabet[] = {'I',' ', 'k','n','o','w',' ','a','l','l',' ','a','b','o','u','t',' ','p','r','o','g','r','a','m','i','n','g','!','\0'}; #include <stdio.h> int main() {int c;do{printf("請(qǐng)輸入文檔的結(jié)尾標(biāo)志");}while((c=getchar())!='\0');printf("已得到文檔結(jié)束標(biāo)志\n");return 0; }'eof'文件結(jié)束符
#include <stdio.h> int main() {int c;do{printf("請(qǐng)輸入文檔的結(jié)尾標(biāo)志");}while((c=getchar())!=EOF);printf("已得到文檔結(jié)束標(biāo)志\n"); //Ctrl+Z然后回車return 0; }在控制臺(tái)輸入的時(shí)候,操作系統(tǒng)將Ctrl+Z翻譯為文檔結(jié)束符。
總結(jié)
以上是生活随笔為你收集整理的【心得】Ctrl+Z、\n、\0、eof的区别和用法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: IBM收购Rational一年总结
- 下一篇: LVS(三)lvs+keeplive