fgets和scanf的區別
阿新 • • 發佈:2019-02-06
1、測試使用scanf的一個例子:
#include "stdio.h"
#include "string.h"
int main()
{
char name[10];
scanf("%s", name);
puts(name);
return 0;
}
編譯、呼叫如下:
可以看到第二次,由於輸入的字串長度,導致Abort
2、同樣的一個fgets的例子:
#include "stdio.h" #include "string.h" int main() { char name[10]; fgets(name, 10, stdin); puts(name); return 0; }
編譯、呼叫如下:
並沒有像scanf那樣出現Abort的情況,而是對字串進行了截斷
3、對比scanf和fgets:
a) scanf不限制使用者的輸入,導致會出現上面測試例子的Abort
fgets限制使用者的輸入,超過之後進行截斷字串的操作,避免了Abort,但是要設定一個緩衝區長度值
b) scanf可以使用諸如scanf("%d/%d", &x, &y),這樣的形式,讓使用者只需要輸入1/3便可以分別得到x、y的值:
#include "stdio.h" int main() { int x; int y; scanf("%d/%d", &x, &y); printf("x value : %d, y value : %d\n", x, y); return 0; }
但是fgets,無論如何,每次都只能讀入一個變數,而且只能是字串(畢竟說是str嘛!),像下面這樣的形式,編譯是通不過的:
#include "stdio.h"
int main()
{
int x;
fgets(x, sizeof(x), stdin);
printf("x value : %d", x);
return 0;
}
c)字串中的空格
scanf用%s接收字串的時候,遇到空格就會停止。如果想輸入多個單詞,需要多次呼叫scanf()
fgets()直接接收字串中的空格
4、總結
由於3提到的一些區別,所以在使用scanf()和fgets()的時候,要注意情況。