问题
I know that the code will not work (program is not complete, I am at the beginning in creating a linked list), but I noticed something weird.
#include <stdio.h>
struct mychar {
char value;
struct mychar *nextPtr;
};
typedef struct mychar Mychar;
void instructions();
void append(Mychar **, char );
int main(){
instructions();
Mychar *startPtr = NULL;
unsigned int choice;
do {
scanf("%d",&choice);
if (choice==1){
char newchar;
printf("\nWrite the character you want to add.");
printf("\n> ");
scanf("\n%c", &newchar);
append(&startPtr, newchar);
} else if (choice==2){
} else {
printf("\nError, try again.\n");
//main();
instructions();
}
} while (choice!=3);
printf("\nEnd of run.\n");
}
void instructions(){
printf("\nSelect operation. 1 to add, 2 to remove, 3 to exit.");
printf("\n> ");
}
void append(Mychar **sPtr, char newvalue){
Mychar *newlinkPtr = calloc (1, sizeof(Mychar));
Mychar *previousPtr = NULL;
Mychar *currentPtr = *sPtr;
while(*sPtr!=NULL && newvalue > currentPtr->value){
previousPtr = currentPtr;
currentPtr = currentPtr->nextPtr;
}
}
Output:
Select operation. 1 to add, 2 to remove, 3 to exit.
> 1
Write the character you want to add.
> a
It stucks forever after I write 'a'. Why?
EDIT:
I think I got it. It's for the \n
that I put in the scanf. I usually put the \n
to avoid scanf bugs. But I must not have understood when should I use it and when not.
So now my question is... when should I use \n
or the space inside scanf
?
来源:https://stackoverflow.com/questions/62071579/scanf-makes-do-while-loop-stuck