scanf in while循环不评估第一个信息块

时间:2015-04-12 23:17:08

标签: c

尝试让scanf迭代并使用isdigit评估字符串的每个部分。然而它似乎正在跳过第一个'块?从而抵消了一切。关于我做错了什么的建议?

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 个答案:

答案 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;
}

答案 1 :(得分:1)

结束了这个简单的代码,因为我的知识水平......嗯......简单 。感谢有关迭代和第二次扫描的帮助,它将驱使我超越边缘!

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