字符串到int数组

时间:2016-04-07 22:13:32

标签: c arrays string int

我已经研究了一段时间,但我一直得到{0,0,0,0,0}或{2751685,2751685等}或{57,58,59,60等}

  void getGuess(int guess[], int length) {
        char thisGuess[length]; 
        int i=0;
        printf("Enter your guess.\n");
        scanf("%s", &thisGuess);

        for(i=0; i<length; i++) {
            printf("the guess = %d\n",(int)thisGuess[i]) ;
            guess[i] = (int)(thisGuess)-48;

            printf("%d  ", guess[i]);
        }
  }

我想输入一个字符串,12345,并且得到它

 guess[0] = 1
 guess[1] = 2
 guess[2] = 3 
 etc

我的代码建议?

1 个答案:

答案 0 :(得分:0)

char数组的长度通常不等于它包含的C风格字符串的长度。

void getGuess(int guess[], int length) {
    char thisGuess[length]; 
    size_t i = 0;
    printf("Enter your guess.\n");
    scanf("%s", thisGuess); // a char *, rather than a char (*)[length] is expected
    size_t guessLength = strlen(thisGuess);
    for(i = 0; i < guessLength; i++) {
        printf("the guess = %d\n", thisGuess[i]);
        guess[i] = thisGuess - '0';
        printf("%d  ", guess[i]);
    }
}

或者,添加

if(!isdigit(thisGuess[i]))
    continue;

以避免潜在的越界访问。