2015-04-12 70 views
-1

試圖讓scanf迭代和評估字符串的每個部分與isdigit。但它似乎在跳過第一個'塊',從而抵消了一切。關於我在做什麼錯誤的建議?scanf在while循環中不評估第一個信息塊

int main (void) { 
    int icount = 0; 
    int c = 0; 
    int compare = 0; 
    int len = 0; 
    char s[256] = ""; 
    printf("Enter a string:\n\n"); 
    while (scanf("%s", s) == 1) { 
     scanf("%255s", s); 
     len = strlen(s); 
     printf("the string is %d characters long\n", len); 
     while (len > 0) { 
      printf("c is on its s[%d] iteration\n", c); 
      if (isdigit(s[c])) { 
      compare = compare + 1; 
      } 
      c++; 
      len--; 
     } 
     if (compare == strlen(s)) { 
      icount = icount + 1; 
     } 
     c++; 
    } 
    printf("\ni count is %d\n", icount); 
    return 0; 
} 

當我運行它,我不斷收到回數據是這樣的:

./a 
Enter a string: 
17 test 17 
the string is 4 characters long 
c is on its s[0] iteration 
c is on its s[1] iteration 
c is on its s[2] iteration 
c is on its s[3] iteration 
the string is 2 characters long 
c is on its s[5] iteration 
c is on its s[6] iteration 
i count is 0 
+2

爲什麼你'scanf()'兩次,是否是一個錯字?我的意思是複製粘貼問題。 –

+0

在while(scanf(...)== 1){'?')後面移除'scanf()我想,你還需要在循環的某個地方將'c'重置爲0。 –

+0

不是不是一個錯字我認爲我必須使用第一個scanf作爲我的條件,第二個作爲循環內實際發生的事情? – sandyman

回答

1

結束隨着這個簡單的代碼,因爲我的知識水平是...好...簡單的 。感謝這次迭代和第二次scanf的幫助,它正在推動我越過邊緣!

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

int main (void) { 
    int icount = 0; 
    int c = 0; 
    int compare = 0; 
    char s[256] = ""; 
    printf("Enter a string:\n\n"); 
    while (scanf("%255s", s) == 1) { 
     compare = 0; 
     for (c = 0 ; s[c] != '\0' ; c++) { 
      if (isdigit(s[c])) { 
      compare = compare + 1; 
      } 
     } 
     if (compare == strlen(s)) { 
      icount = icount + 1; 
     } 
    } 
    printf("%d integers\n", icount); 
    return 0; 
} 
1

從上面的意見,我相信這可能是你在找什麼

#include <ctype.h> 
#include <stdio.h> 

int main (void) 
{ 
    int icount; 
    int index; 
    char string[256]; 

    printf("Enter a string:\n\n"); 

    icount = 0; 
    while (scanf("%255s", string) == 1) 
    { 
     int isNumber; 

     isNumber = 1; 
     for (index = 0 ; ((string[index] != '\0') && (isNumber != 0)) ; ++index) 
     { 
      printf("index is on its string[%d] iteration\n", index); 
      if (isdigit(string[index]) == 0) 
      isNumber = 0; 
     } 
     if (isNumber != 0) 
      icount += 1; 
    } 
    printf("\nicount is %d\n", icount); 

    return 0; 
} 
+0

看起來像肯定會工作。我用一些非常簡單的東西去了,因爲我在C這方面的知識水平很好......簡單... – sandyman