我正在编写一个由客户端和服务器通信组成的 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/