2017-09-25 42 views
1

這裏在read()函數中我使用getchar()它只讀取一個字符。它打破循環,即使在,而條件()是事實,但getchar_unlocked(),直到給定的條件未能 代碼是計算像最大值讀取字符:爲什麼getchar()不起作用,但getchar_unlocked()在讀取字符串字符時讀取主函數?

input : 
4 
8-6+2+4+3-6+1 
1+1+1+1 
2+3+6+8-9 
2+7+1-6 

output : 
10 //(which is max value of 3rd string) 

代碼:

#include <stdio.h> 

inline int read(int *value) { 
    char c, c1 = '+'; 
    *value = 0; 
    c = getchar_unlocked(); 
    while ((c >= '0' && c <= '9') || c == '+' || c == '-') { 
     if (c == '+' || c == '-') c1 = c; 
     else *value = (c1=='+' ? *value + (c-'0') : *value - (c-'0')); 
     c = getchar_unlocked(); 
    } 
    return *value; 
} 

int main() 
{ 
    int n, max=0, val; 
    scanf("%d", &n); 
    char x = getchar(); 
    while(n--) { 
     read(&val); 
     max = val>max?val:max; 
    } 

    printf("%d", max); 
    return 0; 
} 
+0

當出現的getchar'之間的差異的唯一時間()'和'getchar_unlocked()'是在多線程程序。否則,他們的行爲是一樣的。因此,您的診斷似乎不太可能和/或難以置信。請確定您使用的平臺(o/s和編譯器)。請注意,編寫一個函數'read()'是在POSIX程序中實現的。 –

+0

'getchar'和'getchar_unlocked'都返回一個'int',而不是'char'。 (這不是你的問題,但是養成使用'int'的習慣是很好的。) – rici

+0

爲了便於閱讀和理解:1)分開代碼塊(for,if,else,while,do ... while,開關,外殼,默認)通過一個空行。 2)通過2或3個空白行分開函數(保持一致)3)遵循以下公理:*每行只有一條語句和(最多)一條語句的變量聲明* – user3629249

回答

0

以下提議代碼:

  1. 完全編譯
  2. 執行所需功能
  3. 正確處理比0 ... 9其他字符和「+」和「 - 」
  4. 正確檢查I/O錯誤
  5. 被格式化以方便閱讀和理解
  6. 文件爲什麼每個頭文件包含
  7. 使用不與C庫名稱衝突
  8. 正常終止格式字符串printf()所以數據會立即顯示在終端上的功能名稱。
  9. 如果輸入不包含足夠的行以匹配第一行上的數字,仍然存在潛在的問題。

現在推薦碼:

#include <stdio.h> // scanf(), getchar() 
#include <limits.h> // INT_MIN 
#include <ctype.h> // isdigit() 
#include <stdlib.h> // exit(), EXIT_FAILURE 


inline int myRead(void) 
{ 
    int c; 
    char c1 = '+'; 

    int value = 0; 

    while((c = getchar()) != EOF && '\n' != c) 
    { 
     if (c == '+' || c == '-') 
      c1 = (char)c; 

     else if(isdigit(c)) 
      value = (c1=='+' ? value + (c-'0') : value - (c-'0')); 
    } 
    return value; 
} 


int main(void) 
{ 
    int n; 
    int max = INT_MIN; 
    int val; 

    if(1 != scanf("%d", &n)) 
    { 
     fprintf(stderr, "scanf for number of following lines failed"); 
     exit(EXIT_FAILURE); 
    } 

    // implied else, scanf successful 

    while(n--) 
    { 
     val = myRead(); 
     max = val>max?val:max; 
    } 

    printf("%d\n", max); 
    return 0; 
}