user3032010
user3032010

Reputation: 47

scanf() function is not holding the screen for user to enter data

I have used scanf() to hold the screen and take input from user in a multi threaded client side socket program. scanf() is not holding the screen here and user is not able to enter data. The code of thread function is is:

void *send_data(void *num)
{
     int *sock_s=(int *) num;
     int sock=*sock_s;
     char msg[50];
     printf("Enter data:");


     while(1) {
          scanf("%s",msg);
          if(strcmp(msg,"exit")==0)
          {
               break;
          }
          send(sock_s,msg,sizeof(msg),0);
     }
     send(sock,msg,sizeof(msg),0);
}

and the code create tthis thread is:

     status_s=pthread_create(&thread_s,NULL,send_data,(void *)&sock);
            if(status_s==0)
                    printf("sending");

Upvotes: 0

Views: 592

Answers (3)

S Raghav
S Raghav

Reputation: 1526

try this and see whether it works

     printf("Enter data:");
      scanf("\n%s",msg);

while(strcmp(msg,"exit")!=0)
{
   send(sock_s,msg,sizeof(msg),0);
        scanf("\n%s",msg);


}

i think there might be some problem with the while loop

Upvotes: -1

Lundin
Lundin

Reputation: 213960

  • You leave trailing line feed characters in stdin. This question is such a FAQ, it gets asked at least 5 timer per day. Search for scanf on this site... Solution: scanf(" %s", msg); or similar.
  • You can't use plain scanf and similar library functions from inside a thread, they are not thread-safe.
  • The way you use it, scanf is vulnerable and will get buffer overruns.

Upvotes: 2

m1o2
m1o2

Reputation: 1629

The buffer might have a "\r" or "\n" in it. we need to flush the input buffer in order to remove it.

use fflush(stdin) function to flush the buffer.

fflush(stdin)  
scanf("%s", msg );  

Edit: Did you tried to use fgets instead of scanf ?

fgets(msg);

Upvotes: 0

Related Questions