将数组传递给函数时的exception行为

#include  #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]; } 

输出:::

替代文字

当我输入整数元素时,输出是OK。但是当我输入一个像1.5这样的浮点值时,它没有要求其他元素,而O / P如图所示。我认为它应该隐含地将类型转换为1.5 1但它没有发生..你能告诉我为什么会这样吗? 有关编译器的所有信息如图所示。

当您扫描scanf("%d")一个类似1.5的值时,扫描将停在小数点并返回1。

下次调用scanf ,指针仍将指向小数点,扫描将立即返回,因为没有要扫描的数字。

您应该检查scanf的返回值 – 它为您提供成功扫描的项目数,最初为小数点前1的1 ,从那时开始为0。

scanfscanf代表“扫描格式化”,我保证你找不到比用户输入更多未格式化的内容。

研究调查线路输入的fgets 。 这是我经常用于此目的的函数的副本:

 #include  #include  #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; } 

一旦你开始使用该function,你可以根据自己的内容进行sscanf ,更容易处理错误。

发生的事情是scanf在看到'.'时停止读取整数'.' 字符,并将其保留在输入缓冲区中。 然后对scanf后续调用失败,因为下一个字符是'.' 而不是可解析为整数的东西。

你是如何解决这个问题的? 第一步是忘记你曾经听说过scanf并且总是使用fgets读取整行输入,然后在将它们读入字符串缓冲区后处理它们。 您可以将sscanf用于此目的,但像strtol这样的强大function会更好。

缓冲区问题 – 我认为剩下的部分(.5)仍然在缓冲区上。 使用flushall(); 在你的scanf("%d..