mardi 28 novembre 2017

Scanf to dynamic array with strings

Im trying to read numbers from input to dynamic array. From input I should read numbers like this { 1, 2, 3, 4, 5, 6}

while(1){
res = scanf("%1s",c);
  if ( strcmp(c,"{") || res == 0)
  {
    printf("Bad input.\n");
    free(arr);
    return 1;
  }
    while ( 1 ){
    res=scanf(" %d%1s ",&x,c);
      if ( res == 2 && ( !strcmp(c,",") || !strcmp(c,"}") )){
        arr[cnt++]=x;
        counter++;
        if(x<0){
          printf("Bad input.\n");
          free(arr);
          return 1;
        }
        if(res != 2){
        printf("Bad input.\n");
        free(arr);
        return 2;
        }
        if(cnt >= size);{
        size +=2;
        arr=(int*)realloc(arr,size*sizeof(int));
        }
        if ( !strcmp(c,"}")){
          break;
        }
      }
      if ( res != 2 || strcmp(c,",") || strcmp(c,"}")){
        printf("Bad input. %d - %s\n",res,c);
        free(arr);
        return 3;
      }





    }
break;

} But somehow when I type {1,2,3} its still show me bad input with return 3 even when I typed , and } ... And res == 2 too and c is , too ... It only read 1 and then it stopped ... Any ideas to help ?

Aucun commentaire:

Enregistrer un commentaire