#11822: C語言如何用scanf("%c",&input)模擬scanf("%d",&input)輸入?


zzxxxcccc (node)

學校 : 明新科技大學
編號 : 62118
來源 : [1.34.231.24]
最後登入時間 :
2022-03-20 17:01:10
a038. 數字翻轉 | From: [220.132.127.86] | 發表日期 : 2017-03-17 11:28

這題直接用%d就可以直接讀到三題題目 就可以處理出答案

可是我發現用%c一個字一個字讀入處理 在加起來變成結果最省事

 

目前遇到的問題是

while (( input >='0')&&( input <='9' ))

{

 //load and process

}

 

可是在解題中永遠會超時killed

後來我內部放watchdog 假如跑1000次 就跳出 輸出1000

還真的跑出來都是1000 

代表他輸入的數字永遠都在ASCII 0 ~ 9

讓我不能用%c方式讀到結尾

只能用%d直接讀整個數字串

 

請問怎麼會這個樣子呢?

這是我第一題遇到不能直接用讀字元判斷讀取結束跳出的...

我想不透%c都讀不完 那用%d 函數是怎麼知道讀的數字的結尾的?

 

 

 
#11823: Re:C語言如何用scanf(


zzxxxcccc (node)

學校 : 明新科技大學
編號 : 62118
來源 : [1.34.231.24]
最後登入時間 :
2022-03-20 17:01:10
a038. 數字翻轉 | From: [220.132.127.86] | 發表日期 : 2017-03-17 12:55

這題直接用%d就可以直接讀到三題題目 就可以處理出答案

可是我發現用%c一個字一個字讀入處理 在加起來變成結果最省事

 

目前遇到的問題是

while (( input >='0')&&( input <='9' ))

{

 //load and process

}

 

可是在解題中永遠會超時killed

後來我內部放watchdog 假如跑1000次 就跳出 輸出1000

還真的跑出來都是1000 

代表他輸入的數字永遠都在ASCII 0 ~ 9

讓我不能用%c方式讀到結尾

只能用%d直接讀整個數字串

 

請問怎麼會這個樣子呢?

這是我第一題遇到不能直接用讀字元判斷讀取結束跳出的...

我想不透%c都讀不完 那用%d 函數是怎麼知道讀的數字的結尾的?

 

 

以下就是我的程式碼,我後來想說不想再探討是什麼原因了,這種鬼打牆很浪費時間,就用%d的寫法寫出來通過了

假如,真的有人有用我這種概念來寫,又有時間或知道為什麼我讀不到,請回應讓我知道,tks.

 

#include <stdio.h>

#include <stdlib.h>

 

int judgeCoutinue( int inputNum )

{

    if( ( inputNum >= '0' ) && ( inputNum <= '9' ) )

        return 1;

    return 0;

}

int main()

{

    char inputNum;

    while( scanf( "%c", &inputNum ) != EOF )

    {

        unsigned long long int result = 0;

        unsigned long long int base = 1;

        while( judgeCoutinue( inputNum ) ) // use 0 ~ 9  range of ascii , because '\n' didn't work.

        {

            result = result + ( inputNum - '0' ) * base;

            base *= 10;

            scanf( "%c", &inputNum );

        }

        printf( "%llu\n", result );

    }

    return 0;

}

 



 
ZeroJudge Forum