2015-11-29 23 views
-1

需要查找字符串中的所有数字。 (54g不是数字等)并导入到数组中。如何将数字导入数组?以及如何摆脱87)等?将字符串中的所有数字导入到C中的数组中

#include "stdio.h" 
int main() { 
    char *pS; 
    int i; 
    char str[100]; 
    short isn = 0; 
    gets(str); 
    pS = str; 
    int a[100]={0}; 
    i=0; 
    while (*pS) { 
     if (*pS >= '0' && *pS <= '9') { 
      isn = 1; 
      printf("%c", *pS); 
     } 
     else { 
      if (isn) { 
       isn = 0; 
       printf(" "); 
      } 
     } 
     pS++; 
    } 
    return 0; 
} 
+3

您可以发布样本输入:如果是这样的话,我会首先所有非数字字符转换为普通字符值(接任何非数字字符),然后用strtok来标记字符串处理这个期望的输出? – joao

回答

1

我不是您的需求十分清楚,但根据您发布的代码似乎想要把所有相邻的数字为单值和之间忽略任何非数字。

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

int main(int argc, char* argv[]) 
{ 
    char str[100]; 
    char* s; 
    int a[100]; 
    int count; 
    int len; 
    int i; 

    fgets(str, sizeof(str), stdin); 

    /* change all non-digits to spaces */ 
    len = strlen(str); 
    for (i = 0; i < len; ++i) { 
     if (!isdigit(str[i])) 
      str[i] = ' '; 
    } 

    count = 0; 

    /* tokenize on spaces and append to array */ 
    s = strtok(str, " "); 
    while (s != NULL) { 
     a[count++] = atoi(s); 
     s = strtok(NULL, " "); 
    } 

    /* output final array */ 
    for (i = 0; i < count; ++i) 
     printf("%d\n", a[i]); 

    return 0; 
} 
+0

正是我需要的。谢谢! – Bran

相关问题