0

I am working on a program and I have to send one char at a time through a socket. The connection work fine and the chars are sending but when I have to print them to stdout, I cant manage to print them without a newline.

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
                }

One more mention: the client send chars without waiting for ENTER from stdin.

Any hints? Thanks

4

3 回答 3

5

1) Don't lie to read - it tends to nearly always lead to BAD things:

                char buff[2];
                nb = read(connfd, buff, 4096);

This should be: char buff[2]; nb = read(connfd, buff, 1);

2) You need to terminate the string:

buff[1] = 0; 

2a) printf("%s", buff) will not actually display anything, because there is no newline to force the buffered data to be actually written to the screen - use fflush(stdout); to force it.

3) Reading characters without waiting for "enter" is not possible in standard C++ (or C). May I suggest you look at the ncurses package of functions?

于 2013-09-19T16:21:23.217 回答
2
                printf("%s\n",buff);

The %s format specifier is only for C-style strings. Since buff is not a C-style string, this is wrong. Also:

                char buff[2];
                nb = read(connfd, buff, 4096);

How can you read up to 4096 characters into a buffer that's only big enough for 2? You probably want:

                char buff[4096];
                nb = read(connfd, buff, 4096);
                if (nb < 0){
                    printf("The client disconected\n");
                    break;
                }
                for (int i = 0; i < nb; ++i)
                   putchar(buff[i]);
                fflush(stdout);
于 2013-09-19T16:21:03.233 回答
1

You need to flush the buffer. After your printf call, also call fflush(stdout).

Also, since you are trying to print 1 character at a time, you have a few other problems:

char buff; // you wanted to read 1 character at a time
nb = read(connfd, &buff, 1); 
if (nb < 1)
{
    printf("The client disconected\n");
    break;
}
printf("%c", buff);
fflush(stdout);
于 2013-09-19T16:20:12.697 回答