c - 使用 scanf 时无限循环

标签 c client-server

我正在编写一个由客户端和服务器通信组成的 C 程序。在客户端文件中,我使用 scanf("%79[0-9a-zA-z ]", message); (接受数字、字母和空格)扫描用户的输入以发送到服务器,但是我得到一个无限循环。下面是使用它的代码部分:

 while(1)
    {
        printf("Enter message : ");
        scanf("%79[0-9a-zA-z ]", message); 

    if( send(sock , message , strlen(message) , 0) < 0)
    {
        puts("Send failed");
        return 1;
    }

    //Receive a reply from the server
    if( recv(sock , server_reply , 2000 , 0) < 0)
    {
        puts("recv failed");
        break;
    }

    puts("Server reply :");
    //printf("\nServer reply : %s " ,server_reply);
    puts(server_reply);
}
exit(0); 
close(sock);

输出由连续的“Enter message”和“server reply”组成。

最佳答案

代码需要消耗新行@BLUEPIXY

while(1) {
    printf("Enter message : ");
    scanf("%79[0-9a-zA-z ]", message); 

    // Now the \n needs to be read
    int ch = fgetc(stdin);
    ...
}

更好的代码会添加检查

while(1) {
    printf("Enter message : ");
    fflush(stdout); // insure potentially buffered data is outputted

    if (scanf("%79[0-9a-zA-z ]", message) != 1) {
      puts("Nothing read");
      break;
    }

    int ch = fgetc(stdin);
    if (ch == `'\n') {
      ; // good: new line
    } else if (ch == EOF) {
      break; // no more input or input error
    } else {
      puts("Unexpected input");
      break;
    }
    ...
}

更好的代码将使用 fgets()

char buf[81];
while (1) {
    printf("Enter message : ");
    fflush(stdout);

    if (fgets(buf, sizeof buf, stdin) == NULL) break;
    char ch;
    if (sscanf(buf, "%79[0-9a-zA-z ] %c", message, &ch) != 1) {
      puts("Nothing or too much read");
      break;
    } 
    ...
}

关于c - 使用 scanf 时无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42739667/

相关文章:

C 基础编程,它不会在 if else if 算法中打印值

c - 带有 `df` 的可用 block

java - 使用阻塞 IO 的多线程会损坏 Java 中的文件

gwt - ServiceAsync接口(interface)背后的底层技术是什么?

ios - 我的 iOS 应用应该使用什么类型的数据存储?

close() 没有正确关闭套接字

c - 尝试 mmap 设备的 BAR-0 时出现 "Bad file descriptor"错误

c - Timer1 作为实时时钟的精度,16F 上有 PIC 中断*

C 库由异步 DNS 解析器组成

java - Java 中的 DSA 与 RSA 以及 AES128 与 AES256 加密