Scanf makes do_while loop stuck

僤鯓⒐⒋嵵緔 提交于 2020-06-17 10:07:34

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!