我已经进行了一段时间的研究,但是我不断收到{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
关于我的代码的建议?
最佳答案
一个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;
以避免潜在的出站访问。
关于c - 字符串到整数数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36488149/