C語言 gets()和scanf()函式的區別

2022-07-22 03:33:14 字數 1018 閱讀 8295

scanf( )函式和gets( )函式都可用於輸入字串,但在功能上有區別。若想從鍵盤上輸入字串"hi hello",則應該使用__gets__函式。

gets可以接收空格;而scanf遇到空格、回車和tab鍵都會認為輸入結束,所有它不能接收空格。

char string[15]; gets(string); /*遇到回車認為輸入結束*/

scanf("%s",string); /*遇到空格認為輸入結束*/

所以在輸入的字串中包含空格時,應該使用gets輸入。

scanf和gets獲取字串時的區別

在c語言中,能構獲取字串的函式至少有兩個:

1.scanf()

所在標頭檔案:stdio.h

語法:scanf("格式控制字串",變數位址列表);

接受字串時:scanf("%s",字元陣列名或指標);

2.gets()

所在標頭檔案:stdio.h

語法:gets(字元陣列名或指標);

兩者在接受字串時:

1.不同點:

scanf不能接受空格、製表符tab、回車等;

而gets能夠接受空格、製表符tab和回車等;

2.相同點:

字串接受結束後自動加'\0'。

例1:#include

main()

依次鍵入asd空格fg回車,asd空格fg回車,則ch1="asd\0",ch2="asd fg\0"。

例2:#include

main()

依次鍵入asdfg回車,asdfg回車,

則ch1="asdfg\0",c1='\n',ch2="asdfg\0",c2需輸入。

scanf :當遇到回車,空格和tab鍵會自動在字串後面新增'\0',但是回車,空格和tab鍵仍會留在輸入的緩衝區中。

gets:可接受回車鍵之前輸入的所有字元,並用'\n'替代 '\0'.回車鍵不會留在輸入緩衝區中

gets()用到讀取字串,用回車結束輸入 

scanf()可以讀取所有型別的變數

C語言 gets()和scanf()函式的區別

scanf 函式和gets 函式都可用於輸入字串,但在功能上有區別。若想從鍵盤上輸入字串 hi hello 則應該使用 gets 函式。gets可以接收空格 而scanf遇到空格 回車和tab鍵都會認為輸入結束,所有它不能接收空格。char string 15 gets string 遇到回車認為輸...

C語言 gets()和scanf()函式的區別

scanf 函式和gets 函式都可用於輸入字串,但在功能上有區別。若想從鍵盤上輸入字串 hi hello 則應該使用 gets 函式。gets可以接收空格 而scanf遇到空格 回車和tab鍵都會認為輸入結束,所有它不能接收空格。char string 15 gets string 遇到回車認為輸...

C語言 gets()和scanf()函式的區別

scanf 函式和gets 函式都可用於輸入字串,但在功能上有區別。若想從鍵盤上輸入字串 hi hello 則應該使用 gets 函式。gets可以接收空格 而scanf遇到空格 回車和tab鍵都會認為輸入結束,所有它不能接收空格。char string 15 gets string 遇到回車認為輸...