一次打印从一个套接字接收的字符

Dor*_*usu 0 c c++ sockets linux

我正在开发一个程序,必须一次通过套接字发送一个字符。连接工作正常,字符正在发送,但是当我必须将它们打印到标准输出时,我无法在没有换行符的情况下进行打印。

for ( ; ; ) {
            nb = select(connfd+1, &read_set, NULL, NULL, NULL);
            if (nb<=0) {
                printf("Error\n");
            }else{
                if (FD_ISSET(connfd, &read_set)) {
                    char buff[2];
                    nb = read(connfd, buff, 4096);
                    if (nb < 0){
                        printf("The client disconected\n");
                        break;
                    }
                    printf("%s\n",buff); // this prints them with a new line between each char.Removing the \n will make it work only by hitting enter
                    //fputs(buff,stdout); //does the same as printf without \n
                }
Run Code Online (Sandbox Code Playgroud)

再说一遍:客户端发送字符而不必等待stdin的ENTER。

有什么提示吗?谢谢

Mat*_*son 5

1)不要说谎read-往往会导致坏事:

                char buff[2];
                nb = read(connfd, buff, 4096);
Run Code Online (Sandbox Code Playgroud)

应该是:char buff [2]; nb = read(connfd,buff,1);

2)您需要终止字符串:

buff[1] = 0; 
Run Code Online (Sandbox Code Playgroud)

2a)printf("%s", buff)实际上不会显示任何内容,因为没有换行符可以强制将缓冲的数据实际写入屏幕- fflush(stdout);可以强制使用。

3)在标准C ++(或C)中,不等待“输入”而无需读取字符是不可能的。我可以建议您看一下ncurses功能包吗?