2013-09-30 51 views
0

客戶端:轉換爲整數字符緩衝區在插座

char buf[1024]; 
int packetAmt = fileSize/PACKETSIZE; 
cout<<"Number of packet amounts: "<<packetAmt<<endl; 

// send packet amount to serv 
ibytessent=send(s,itoa(packetAmt,buf,10),sizeof(buf),0); 

服務器端:

char szbuffer[1024]; 
if((ibytesrecv = recv(s1,szbuffer,sizeof(szbuffer),0)) == SOCKET_ERROR) 
    throw "Receive error in server program\n"; 
cout << "This is the number of packets sent: " << szbuffer << endl; 
packetAmt=atoi(szbuffer); 
cout << "This is the number of packets sent: " << packetAmt<< endl; 

的整數字符數組轉換成整數的發送的字符串不匹配後返回。但是,打印字符串將返回正確的值。我也嘗試過使用strtol函數。將整數轉換爲char數組時會發生錯誤嗎?

+0

你得到的數字與你的期望值有多接近? –

+0

我期待288,但我得到了120。 – Sebastien

+0

這真的很奇怪,特別是因爲你同時顯示字符串和轉換後的值;這意味着「atoi」完全被打破,我拒絕相信。必須比你展示的代碼更多。 –

回答

0

我意識到問題的根源,我有以下代碼行將發送者的地址信息轉換爲十六進制值。以下所有代碼都將整數值解釋爲十六進制而不是十進制。

cout<<"accepted connection from "<<inet_ntoa(ca.ca_in.sin_addr)<<":" 
<<hex<<htons(ca.ca_in.sin_port)<<endl; 

感謝您的意見,它確實有助於縮小問題的範圍!

1

atoi將在到達第一個非數字字符時停止。如果在接收緩衝區中沒有終結符,它可能會超過數字的預期結尾。它似乎也沒有在發送者的緩衝區中放置終止符。

相關問題