因此,对于一个赋值,我应该检查来自用户的输入,并确定是否:
1.如果输入中有字符:我打印一条错误消息,说这是一个无效的输入,并要求再次输入,直到它是有效的
1.如果输入中的数字少于6位:我打印一条错误消息,指出还剩x位数,并再次请求输入,直到它有效为止
int main() {
int solutionArray[6];
int guessArray[6];
int indexArray[6];
/*Creating the random numbers and asking for seed*/
int seed;
printf("Enter the integer value of the seed for the game: ");
scanf("%d", &seed);
srand(seed);
/*Adding the randomized integers into solutionArray*/
for(int i = 0; i < 6; i++){
solutionArray[i] = rand() % 10;
printf("%3d", solutionArray[i]);
}
printf("\n");
/*Game interface*/
printf("For each turn enter 6 digits 0 <= digit <= 9 \n");
printf("Spaces or tabs in your response will be ignored. \n");
/*Validating conditions of the user input*/
char input[50];
int error = 0;
int enoughDigits = 0;
do {
printf("Enter your guess, 6 digits: ");
scanf("%s", input);
int numCount = 0;
int remainder = 0;
int maxLength = 6;
// Checking to see if there are any characters other than digits and prints error
for (int i = 0; i < 6; i++) {
if (!isdigit(input[i])) {
printf("ERROR: A character in your guess was not a digit or a white space\n");
printf("\n");
error = 1;
break;
}
}
/*Checking to see if enough digits have been inputted*/
remainder = 6 - numCount;
for (int i = 0; i < 6; i++){
if (isdigit(input[i] == 1)){
numCount++;
if (numCount < maxLength && numCount != 0){
enoughDigits = 1;
}
else{
printf("You need to enter %d digits to complete your guess \n", remainder);
}
error = 1;
}
}
// Print the guess if there are no errors
if (error == 0) {
printf("Your guess was:\n");
for (int i = 0; i < 6; i++) {
guessArray[i] = input[i] - '0';
printf("%2d", guessArray[i]);
}
printf("\n");
}
// Printing results of the guesses
int partialMatches = 0;
int perfectMatches = 0;
for (int i = 0; i < 6; i++) {
partialMatches = 0;
for (int j = 0; j < 6; j++) {
if (solutionArray[i] == guessArray[j]) {
partialMatches++;
break; // Exit inner loop after finding a partial match
}
}
if (solutionArray[i] == guessArray[i]) {
perfectMatches++;
partialMatches--;
}
}
if (perfectMatches == 6){
printf("YOU DID IT! ! \n");
error = 0;
break;
}
printf("%d matches, %d partial matches\n",perfectMatches, partialMatches);
error = 1;
} while (error == 1 || enoughDigits == 1);
return 0;
}
我的问题是,当用户输入例如“123”时,它应该打印出我需要再输入3个数字,但它只打印出“您猜测的字符不是数字或空格”。出于某种原因,它会打印该错误,而不管输入是什么。
下面是我的代码。先谢谢你了!
1条答案
按热度按时间ee7vknir1#
至少这些问题
缓冲区溢出
scanf("%s", input)
不会阻止保存到input[]
时出现太多字符。使用 width。由于input
的大小为50,因此使用宽度49。测试错误
isdigit(input[i] == 1)
当然应该是isdigit(input[i])
来测试input[i]
是否是数字。