//p05.c --- 使用 fgets( ) 先讀入整列字串 //@CopyLeft by tsaiwn@csie.nctu.edu.tw // 這範例只是改用 fgets( ) 讀取資料, 不是使用 scanf( ) // fgets( )讀資料的好處是一定不會被 User 亂輸入搞死掉! // 因為不管輸入啥都是字串, 阿 fgets( ) 就是讀取字串! /// 另一個簡單版是 gets( ), 但是 gets( ) 很危險! 會被駭客利用! Why? // 注意用 fgets讀入的資料, 其尾巴可能有 '\n' ( New Line); 但此例沒影響! // 若使用 gets(buf); 雖簡單且可以, 但因很危險所以建議不要用! Why?? #include #include #include double x; // (注意 1) 變數 variable; // C++ 式的註解 comment char buf[99]; int main( ) { // 大多數 main program 都這樣開頭 printf("Give me x: "); fgets(buf, sizeof(buf), stdin); // stdin 就是鍵盤, 要記得含入 x = atof(buf); // atof() 是宣告在 printf(" sqrt 根號 %f =%f\n ", x, sqrt(x) ); printf("Bye bye!\n Hit ENTER key..."); getchar( ); return 0; // 告知作業系統(OS)表示我們這主程式正常結束 }// main( /*************** Running script D:\test> path C:\Dev-Cpp\bin;%path% D:\test> gcc p05.c D:\test> a.exe Give me x: abcde sqrt 根號 0.000000 =0.000000 Bye bye! D:\test> a Give me x: 9 sqrt 根號 9.000000 =3.000000 Bye bye! D:\test> a.exe Give me x: 2 sqrt 根號 2.000000 =1.414214 Bye bye! D:\test> path C:\TC\BIN;%path% D:\test> tcc p05.c Turbo C++ Version 3.00 Copyright (c) 1992 Borland International p05.c: Turbo Link Version 5.0 Copyright (c) 1992 Borland International Available memory 4106928 D:\test> p05 Give me x: 2 sqrt 根號 2.000000 =1.414214 Bye bye! D:\test> p05.exe Give me x: 2 sqrt 根號 2.000000 =1.414214 Bye bye! D:\test> ********************************/