24h購物| | PChome| 登入
2009-07-19 19:35:52| 人氣14,602| 回應0 | 上一篇 | 下一篇

Scanf

推薦 4 收藏 0 轉貼0 訂閱站台

 

char

1byte

c

-128~127

unsigned

char

1byte

uc

0~255

 

short

2bytes

sh

-32768~32767

 

long

4bytes

l

-2147483648~2147483647

 

double

8bytes

d

1.7E-308~1.7E+308

 

int

2bytes (16bit)

4bytes (32bit)

n

-2147483648~ 2147483647

short

int

2bytes

sn

-32768~32767

long

int

4bytes

ln

-2147483648~ 2147483647

unsigned

int

4bytes

un

0~4294967295

unsigned short

int

2bytes

usn

0~65535

unsigned long

int

4bytes

usn

0~4294967295

 

float

4bytes

f

3.4E-38~3.4E+38

char → %c

(long) int → %d

short int → %hd

unsigned int → %lu

long long int → %lld

unsigned long long int → %llu

float → %f

double → %lf

1.輸入數字(此部份 可由優化輸入的部份代替 自己去看文章)
scanf("%d",&x);

  x要事先宣告,要依照你要的並在""中放入相對應的型態(以上);

  新手易犯 &取址符號一定要加!!

  若沒有放在while()中,就必須在後面加上分號.

2.輸入陣列

   scanf("%s",x);

  一律都是 宣告 char

  讀入的個數.假使是x個,請宣告 char ar[x+1];

  因為讀入之後,會在陣列尾巴補上一個 '\0' 來當作結束

  不用加&

3.重複輸入

   while(scanf("%d %s",&x,y)==2)

   while(scanf("%d %s",&x,y)!=0)

   while(scanf("%d %s",&x,y)!=EOF)

   while(scanf("%d %s",&x,y))

 三者一樣意思,不過要使用第一種==2的話,這個意思為裡面有幾個需要讀入的變數

 這裡就放什麼數字.
!=EOF 是 Ctrl+z+Enter 做結尾 就跳掉(也就是按下這個 就會跳離)

4.神奇的輸入

  (1)while(scanf("%d%c",&n,&c)==2)

      {

       if(c=='\n') break;

       ar[top++]=n;

      }

    這是一個隔'1'個空白的輸入 一直輸入數字 但是不知道什麼時候輸入完畢 (也就是換行的時候結束.) 就用這個方法(非常好用 不用分析字串.)

   記住是1個空白!!

  (2)while(scanf("%5d",&n)==1)

    這個比較難說明.假使輸入的內容如下:

    12345698754 123456 4

    進來的時候,就會被切割成

    12345 69875 4 12345 6 4

    就是讀入 6 個數字

    簡單的說,就是超過5位就切割.

    浮點數也可以while(scanf("%5.2lf",&f)==1)

    小數點之後只讀入2位..自行測試

 5.gets()混用小心

   當一個scanf之後接多個 gets 必須將換行的字元讀掉('\n')

   再scanf("%d",&n);的後面加上

   getchar();/*只讀入一個字元的函式 速度快*/或scanf(" ");

   或直接修改成scanf("%d ",&n);

 

 

台長: 來源不明
人氣(14,602) | 回應(0)| 推薦 (4)| 收藏 (0)| 轉寄
全站分類: 數位資訊(科技、網路、通訊、家電) | 個人分類: 算是技巧 |
此分類下一篇:新發現 I
此分類上一篇:For

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文