LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   why cann't the getchar() return? (https://www.linuxquestions.org/questions/programming-9/why-cannt-the-getchar-return-747218/)

ebd 08-13-2009 03:17 AM

why cann't the getchar() return?
 
hi all
i just want to get a char from getchar(),but the getchar never return regardless how many characters i input and hit enter

here is the program i encounter the problem:

Code:

int main(int argc, char **argv){
    int qid;
    int pid;
    int i;
    key_t key;
    int len;
    struct message msg;
    struct message childMsg;
    char sel;
    if((key=ftok(".",'a')) == -1){
        perror("ftok");
        exit(1);
    }
    if((qid=msgget(key,IPC_CREAT|0666)) == -1){
            perror("msgget");
            return -1;
    }
    printf("get msgQueue:%d\n",qid);
    for(i=0; i<5; i++){
        puts("please enter the message to the queue");
        if((fgets(msg.msg_text,BUFSZ,stdin))==NULL){
            perror("fgets");
            exit(1);
        }
        msg.msg_type = i+1;
        len = strlen(msg.msg_text);
        if(msgsnd(qid,&msg,len,0) < 0){
            perror("message send");
            exit(1);
        }
    }
    printf("please select the message id you want to get:\n");

    for(i=0; i<5; i++){
            sel = getchar();
            if(msgrcv(qid,&childMsg,BUFSZ,sel-'a'+1,0)<0){
                perror("msgrcv");
                exit(1);
            }
            printf("the message is %s\n",childMsg.msg_text);
        }
        exit(0);
}

when the program run to getchar(), i input a char and hit enter, but i doesn't return....

what's the problem? thanks in advance

jeromeNP7 08-13-2009 06:49 AM

Try switching to scanf to get input within the program. Getchar isn't really waiting for any input and it will continue right away even if no input is found immediately. Scanf will wait for input.

Linux

ebd 08-13-2009 07:10 AM

i'll have a try with scanf
but i still wonder why getchar doesnot work as we want

ebd 08-14-2009 01:28 AM

everything goes well afer memseting childMsg everytime before msgrcv
thank you all


All times are GMT -5. The time now is 12:01 AM.