- gets
範例:
char line1[80]; printf("Enter first string : "); gets(line1);
然後compile的時候你會得到警告訊息
the `gets' function is dangerous and should not be used.
這是因為gets沒有停止溢位的機制,所以當你輸入的字元大於array大小,程式就會爆掉
所以不建議使用gets
用此法輸入的字串不含\n(gets會把\n換成\0)。
- fgets
範例:
char line1[MAXSIZE]="", line2[MAXSIZE]=""; printf("Enter first string : "); fgets(line1, sizeof(line1), stdin); printf("%s\n", line1); printf("Enter second string : "); fgets(line2, sizeof(line2), stdin); printf("%s\n", line2);
看似美好,可是當你printf輸入的字串時,會多一行出來
Enter first string : abcd efgh
abcd efgh
Enter second string : abcdefgh
abcdefgh
這是因為fgets會把\n包含進去(然後加個\0)。
- scanf
scanf的缺點是空格之後的就不會列進去
printf ("Enter your family name: "); scanf ("%79s",str); printf ("Enter your age: "); scanf ("%d",i); printf ("Mr. %s , %d years old.\n",str,i); printf ("Enter a hexadecimal number: "); scanf ("%x",i); printf ("You have entered %#x (%d).\n",i,i);- 自己寫
char line1[MAXSIZE]="", line2[MAXSIZE]=""; printf("Enter first string : "); read_string(line1); printf("%s\n", line1); printf("Enter second string : "); read_string(line2); printf("%s\n", line2); void read_string(char *pt) { int i, j=0; char c; for(i=0; i < MAXSIZE-1; i++){ if ((c=getchar()) != '\n' && c != EOF){ pt[j++] = c; } else { break; } } }
沒有留言:
張貼留言