问题
I am trying to write a correct console application for linked list usage, so i need to scan a number of a command in a infinite loop and do something due to switch case option. So i am using scanf for this but the problem is when the next line doesnt contain number it loops and starts printing not even default value.
`while(1)
{
printf("Enter a number of a command.\n");
scanf("%d",&command);
switch(command)
{
case -1:
....
default:
printf("Reenter command.\n");
break;
}
}
It seems like when i am reading the infinite amount of data stack gets rewrited. I know i have to limit the amount of symbols reading, but dont understand how to do this in right way.
Using gcc version 5.4.0 (GCC), c99 on Ubuntu 18.04.2 LTS
回答1:
I don't have enough reputation to comment, but this might be what you are looking for. Also try to be more descriptive. I have pasted your code and the only problem I could find is that when you press enter without inserting a number(i.e. a letter) it skips. This should fix it:
int readInt(const char *message, int min, int max){
int num, control;
do{
printf("%s (%d a %d) :", message, min, max);
control = scanf ("%d", &num);
cleanBufferStdin();
if (control == 0)
{
printf("You should enter a number \n");
}
else{
if(num<min || num>max)
{
printf("Number is invalid.\n");
}
}
}
while(num<min || num>max || control ==0);
return num;
}
void cleanBufferStdin(void)
{
char chr;
do
{
chr = getchar();
}
while (chr != '\n' && chr != EOF);
}
I coded for a bit more, and in another interpretation of your question(this one not only detects if you just pressed enter but if you didnt place an integer i didnt check if negative numbers work) I used this function:
//DONT FORGET TO #DEFINE WRONG_REQUEST_MACRO "SOME MESSAGE"
void readString(const char message*, char arrayChars *, int maxChars){
int stringSize;
unsigned char flag=0;
do{
flag =0;
printf("%s", message);
fgets(arrayChars, maxChars, stdin);
stringSize = strlen(arrayChars);
if (stringSize == 1){
printf("[INFO]Empty request. You just pressed ENTER.\n");
flag=1;
}
if (atoi(arrayChars)==0&&arrayChars[0]!=0){
printf("[INFO]You didn't enter a number.\n");
flag=1;
}
} while (flag == 1);
if (arrayChars[stringSize - 1] != '\n'){
clearBuffer();
}else{
arrayChars[stringSize - 1] = '\0';
}
while (strchr(arrayChars, '\'') != NULL || strchr(arrayChars, '?') != NULL || strchr(arrayChars, '*') != NULL || strchr(arrayChars, '\"') != NULL){
printf("%s ' %s '", WRONG_REQUEST_MACRO, arrayChars);
break;
}
}
this should be used like
int command;
char message[20];//yes this could be used with a char pointer but lets assume op doesnt know how to allocate memory or work with char pointers it wouldn't change that much but if he does know how to do it he will promptly change
readString("something something i suppose\n",message,20);
command=atoi(message);
Welp the last although its filled with debugging "duplicates" should work
来源:https://stackoverflow.com/questions/65065931/is-there-a-way-of-limiting-scanf-in-c