2017-05-20 25 views
-1

私が書いたプログラムで何が間違っているか教えてください。 私は、ユーザーが入力した文字列にある数字で新しい文字列を作成しようとしています。例えばCの文字列から数字を抽出する

:「という文字列を入力します。helloeveryone58985hohohをkgkfgk878788

答え:58985878788

番号が見つからない場合は、その答えはあってはならない。 "という文字列には変化"

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

#define MK 20 
#define ML 81 

void changeStr(char str[],char New[]){ 
    int i,j=0,n; 

    for(i=0;i<) 
} 

int main(){ 
    char str[ML],New[ML]={0}; 
    printf("Enter string: \n"); 
    gets(str); 
    changeStr(str,New); 
    printf("Changed string:\n"); 
    printf("%s",New); 
    if(New[0] == '\0'){ 
     printf("No changes in string.\n"); 
    } 
    return 0; 
} 
+4

これは何ですか?for(i = 0; i <) '? – alk

+0

プログラムにインデントがありません。 –

+0

文字列の最後に0があるので、ループはその文字列がヒットするまで実行されます。あなたが望む関数は 'isdigit'です – stark

答えて

1

これは動作するはずです:

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

#define ML 81 

char *changeStr(char *str) 
{ 
    char *new = NULL;; 
    int i = 0; 
    int length = 0; 

    /* calulating the size to allocate with malloc for new */ 
    while (str[i]) 
    { 
     if (str[i] >= 48 && str[i] <= 57) 
      length++; 
     i++; 
    } 

    /* if no numbers found, return new which is NULL */ 
    if (length == 0) 
     return new; 
    new = malloc(length * sizeof(char)); 
    i = 0; 
    length = 0; 

    /* filling new with numbers */ 
    while (str[i]) 
    { 
     if (str[i] >= 48 && str[i] <= 57) 
     { 
      new[length] = str[i]; 
      length++; 
     } 
     i++; 
    } 
    new[length] = 0; 
    return new; 
} 

/* I kept the functions you are using in the main, i would not 
    use gets, but it's maybe easier for you to keep it */ 

int main() 
{ 
    char str[ML]={0}; 
    char *New; 

    printf("Enter string: \n"); 
    gets(str); 
    New = changeStr(str); 
    if(!New){ 
     printf("No changes in string.\n"); 
    } 
    else 
    { 
     printf("Changed string:\n"); 
     printf("%s",New); 
    } 
    return 0; 
} 
+0

ありがとう!)@ MIG-23 –

0

それは、あなたが望んでいたものですか?

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

#define MK 20 
#define ML 81 

void changeStr(char str[],char New[]) 
{ 
    int i,iNew = 0; 
    int lenStr = strlen(str); 
    for(i=0;i<lenStr;i++) 
     if (str[i]>= '0' && str[i]<= '9') 
      New[iNew++]=str[i]; 
    New[iNew]=NULL; 
} 

int main() 
{ 
    char str[ML],New[ML]= {0}; 
    printf("Enter string: \n"); 
    gets(str); 
    changeStr(str,New); 

    if(New[0] == '\0') 
    { 
     printf("No changes in string.\n"); 
    } 
    else 
    { 
     printf("Changed string:\n"); 
     printf("%s",New); 
    } 
    return 0; 
} 
+0

ありがとう! @ sudipto.bd –

関連する問題