2015-03-02 73 views
0
string s = "100:T1:R1:170.168.0.9:55555:11111"; 
stringstream ss; 
ss<<s; 
string Temp= ss.str(); 
ss.str(string()); 
char *buff= const_cast<char *>(Temp.c_str()); 
I have string in this buff. 
int len; 
len=sendto(sd, buff,sizeof(buff), 0, (struct sockaddr*)&addr, sizeof(addr)); 
cout<<"\n"<<len<<endl; 

當我寫這段代碼時,我得到的長度是8,即我想發送的字符串的8個字符,但是我想發送整個字符串。 所以,請幫助我。發送到函數錯誤:

回答

5

buff被聲明爲char*sizeof(char*)是指針本身的大小,而不是被指向的數據的大小。在你的系統上,指針是8個字節(即你的應用程序是爲64位操作系統編譯的)。

請勿使用sizeof(buff),請使用Temp.length()strlen(buff)改爲(如果您還需要發送空終止符,請添加+1)。

另外,你的stringstream在你的例子中是無用的。

string s = "100:T1:R1:170.168.0.9:55555:11111"; 
int len = sendto(sd, s.c_str(), s.length(), 0, (struct sockaddr*)&addr, sizeof(addr)); 
cout << "\n" << len << endl;