2010-10-15 109 views
0
#include <stdio.h> 
#define SIZE 5 

void func(int*); 
int main(void) 
{ 
    int i, arr[SIZE]; 
    for(i=0; i<SIZE; i++) 
    { 
      printf("Enter the element arr[%d]: ", i); 
      scanf("%d", &arr[i]); 
     }//End of for loop 

    func(arr); 
    printf("The modified array is : "); 

    for(i=0; i<SIZE; i++) 
    printf("%d ", arr[i]); 

    return 0; 

} 

    void func(int a[]) 
{ 
    int i; 

    for(i=0; i<SIZE; i++) 
    a[i] = a[i]*a[i]; 
} 

輸出:::異常行爲而將數組傳遞給一個函數

alt text

雖然我進入整數元素作爲我進入浮點值1.5等的輸出OK.But,它沒有要求其他元素和O/P是如圖所示。我認爲它應該隱含的類型爲1.5到1,但它沒有發生..你可以告訴爲什麼會發生這種情況?所有關於編譯器的信息都顯示在圖中。

+0

讓這是一個不使用'scanf'的教訓。 – 2010-10-15 06:35:07

+0

@R ..我認爲我的問題直到現在我的所有問題都存在一些問題...我沒有在for循環或scanf中發現任何問題。如果你知道更多的東西,那麼你可以告訴我。 – Parikshita 2010-10-15 06:40:27

+0

@R ..ü可能是天才,但我不是..我想2從錯誤中學習,但在這裏重犯錯誤.. ?? – Parikshita 2010-10-15 06:42:16

回答

5

當你scanf("%d")1.5的值將停止掃描,在小數點,並返回1.

下一個一次調用scanf,指針將仍然點小數點和您的掃描將立即返回,因爲沒有數字在那裏掃描。

您應該檢查scanf的返回值 - 它給出了成功掃描的項目數,小數點前爲1,初始值爲1,然後從0開始爲0。

順便說一下,scanf代表「掃描格式」,我保證你找不到任何東西更多未格式化比用戶輸入。

研究調查fgets的線路輸入。這裏有一個功能我經常使用的用於上述目的的一個副本:

#include <stdio.h> 
#include <string.h> 

#define OK  0 
#define NO_INPUT 1 
#define TOO_LONG 2 
static int getLine (char *prmpt, char *buff, size_t sz) { 
    int ch, extra; 

    // Get line with buffer overrun protection. 
    if (prmpt != NULL) { 
     printf ("%s", prmpt); 
     fflush (stdout); 
    } 
    if (fgets (buff, sz, stdin) == NULL) 
     return NO_INPUT; 

    // If it was too long, there'll be no newline. In that case, we flush 
    // to end of line so that excess doesn't affect the next call. 
    if (buff[strlen(buff)-1] != '\n') { 
     extra = 0; 
     while (((ch = getchar()) != '\n') && (ch != EOF)) 
      extra = 1; 
     return (extra == 1) ? TOO_LONG : OK; 
    } 

    // Otherwise remove newline and give string back to caller. 
    buff[strlen(buff)-1] = '\0'; 
    return OK; 
} 

 

// Test program for getLine(). 

int main (void) { 
    int rc; 
    char buff[10]; 

    rc = getLine ("Enter string> ", buff, sizeof(buff)); 
    if (rc == NO_INPUT) { 
     // Extra NL since my system doesn't output that on EOF. 
     printf ("\nNo input\n"); 
     return 1; 
    } 

    if (rc == TOO_LONG) { 
     printf ("Input too long [%s]\n", buff); 
     return 1; 
    } 

    printf ("OK [%s]\n", buff); 

    return 0; 
} 

一旦你與該功能得到一條線,你可以sscanf它到你的心臟的內容,處理錯誤多更輕鬆。

+1

+1正如我在c.l.c上所讀到的:「在某個時刻,某人甚至會寫一些'fgets()'包裝器(對於行爲心理學家來說,研究不同的設計選擇可能會很有趣)。」 – schot 2010-10-15 06:56:10

-2

緩衝區問題 - 我認爲剩下的部分(.5)保留在緩衝區中。 使用flushall();後您scanf("%d..

+3

C沒有'flushall'這樣的函數。 – 2010-10-15 06:35:57

+0

@R - 感謝您將我的注意力帶到了這裏 - 我使用VS編寫了Windows代碼 - 所以我認爲它會起作用。 – Sekhar 2010-10-15 07:16:35

3

發生什麼事scanf當看到'.'字符時停止讀取整數,並將其保留在輸入緩衝區中。然後對scanf的後續調用失敗,因爲下一個字符是'.',而不是可解析爲整數的東西。

你如何解決這個問題?第一步是忘記你曾經聽說過scanf並始終使用fgets來讀取整行輸入,然後在將它們讀入字符串緩衝區後處理它們。你可以使用sscanf來達到這個目的,但是像strtol這樣的強大功能會更好。

+0

thnx R ..我弄錯了.. – Parikshita 2010-10-15 07:32:12