當你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
它到你的心臟的內容,處理錯誤多更輕鬆。
讓這是一個不使用'scanf'的教訓。 – 2010-10-15 06:35:07
@R ..我認爲我的問題直到現在我的所有問題都存在一些問題...我沒有在for循環或scanf中發現任何問題。如果你知道更多的東西,那麼你可以告訴我。 – Parikshita 2010-10-15 06:40:27
@R ..ü可能是天才,但我不是..我想2從錯誤中學習,但在這裏重犯錯誤.. ?? – Parikshita 2010-10-15 06:42:16