2015-04-12 31 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