-1
我正在嘗試使用以下程序從文件描述符'0'(STDIN)中讀取用戶輸入。之前,它沒有問題,但是在程序的其他部分發生了一些變化之後,它在讀取輸入時給我一個分段錯誤。我還刪除了「FD_CLR(0,& readfds)」以查看它是否有效,但它不。你能檢查問題出在哪裏嗎?從STDIN讀取用戶輸入時出現分段錯誤
char *userInput;
FD_ZERO(&masterfds);
FD_SET(0, &masterfds);
FD_SET(udp_con, &masterfds);
maxfds = udp_con;
while(exit == false)
{
readfds = masterfds;
selectFunc = select(maxfds+1, &readfds, NULL, NULL, &tv);
if(selectFunc < 0)
{
message("error in select");
exit = true;
}
else if(selectFunc == 0) //If there is a timeout
{
}
else //If a file descriptor is activated
{
if(FD_ISSET(udp_con, &readfds)) //If there is an activity on udp_con
{
/*read the udp_con via recvfrom function */
}
if(FD_ISSET(0, &readfds)) //If There is an input from keyboard
{
/* When it reaches to this part, the program shows a "segmentation fault" error */
fgets(userInput, sizeof(userInput), stdin);
int len = strlen(userInput) - 1;
if (userInput[len] == '\n')
{
userInput[len] = '\0';
}
string str = userInput;
cout<<"The user said: "<<str<<endl;
commandDetector(str);
FD_CLR(0, &readfds);
}
}
}
如何爲'userInput'聲明,並且任何與完成它在達到這段代碼之前? –
@MarkkuK。對不起,我忘記了添加userInput聲明語句。我剛剛編輯了我的第一篇文章,並在代碼的開頭添加了它。 – Amir