Hello, there is a problem, the essence of it is that there is Edit1 in it, I enter a certain number, this number is multiplied by 100, and I need to transfer it to the server (since I am a client). As I did by examples, they passed there using a char array, but it’s impossible to read the number from Edit1 and add it to this char array. I am new to sockets (use them for the first time), so I will be glad to every advice . I am writing in Borland C ++ Builder 6.

Problem: Read the number from Edit1 and transfer it to the server.

//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "WinSockUDP.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm1 *Form1; //-------------------------------------------------------------------------- - __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void Socket() { const int iReqWinsockVer = 2; WSADATA wsaData; if (WSAStartup(iReqWinsockVer,&wsaData)==0) { Form1->Memo1->Lines->Add("Инициализация библиотеки сокета(Ws2_32.dll) удалась"); SOCKET s; s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (s == INVALID_SOCKET) Form1->Memo1->Lines->Add("При создании сокета возникла ошибка: " + WSAGetLastError()); else Form1->Memo1->Lines->Add("Создание сокета было успешным!"); sockaddr_in sockAddr; sockAddr.sin_family = AF_INET; // Клиент: if(Form1->RadioButton2->Checked) { sockAddr.sin_port = htons(80); sockAddr.sin_addr.S_un.S_addr = inet_addr("169.254.213.26"); Char buf[1019]; /* // Пытался сделать таким методом, не вышло String str = Form1->Edit1->Text; ShowMessage(str); for(int i=0; i<3; i++) buf[i] = str[i]; */ // Токо что и получается, так это передавать числа ручным вводом buf[0] = '3'; while(true) { // Отправляю данные sendto(s, buf, sizeof(buf), 0, (struct sockaddr *)&sockAddr, sizeof(sockAddr)); break; } closesocket(s); if (WSACleanup()!=0) Form1->Memo1->Lines->Add("Освобождение ресурсов WinSock не удалось"); else Form1->Memo1->Lines->Add("Освобождение ресурсов WinSock завершилось успехом"); } // Сервер: else if(Form1->RadioButton1->Checked) { sockAddr.sin_port = htons(80); sockAddr.sin_addr.S_un.S_addr = INADDR_ANY; if (bind(s, (sockaddr*)(&sockAddr), sizeof(sockAddr))!=0) Form1->Memo1->Lines->Add("Связывание адреса с socket'ом не произошло"); else Form1->Memo1->Lines->Add("Связывание адреса с socket'ом было успешным!"); int iSize; char buf[1019]; buf[0] = '0'; // Это для проверки, сменилось ли число while(true) { sockaddr_in client_addr; int iSize = sizeof(client_addr); // Принимаю данные int ret = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&client_addr, &iSize); if(ret == 0) Form1->Memo1->Lines->Add("При отправке данных возникла ошибка"); else { Form1->Memo1->Lines->Add("Данные были доставлены успешно!"); ShowMessage(buf[0]); break; } } closesocket(s); if (WSACleanup()!=0) Form1->Memo1->Lines->Add("Освобождение ресурсов WinSock не удалось"); else Form1->Memo1->Lines->Add("Освобождение ресурсов WinSock завершилось успехом"); } } else Form1->Memo1->Lines->Add("Инициализация библиотеки сокета(Ws2_32.dll) не удалась"); } //--------------------------------------------------------------------------- void __fastcall TForm1::Edit1KeyDown(TObject *Sender, WORD &Key, TShiftState Shift) { if (Key == 13) // Это обработчик события onKeyDown для эдита, 13 - это Enter { INT a = Edit1->Text * 100; Edit1->Text = a; } } //--------------------------------------------------------------------------- void __fastcall TForm1::Button1Click(TObject *Sender) { Socket(); } //--------------------------------------------------------------------------- 
  • tried through char * buf; buf = 3; ? as a last resort did not try through Cmd so - char bufarr [32]; scanf ("% s", bufarr); > Here you can enter. And it is not clear what kind of Form1-> Edit1-> Text is? Well, either in the most extreme case like this - const char * buffer; buffer = str.c_str (); ? In general, in my opinion, it is possible and immediately so - sendto (s, string.c_str (), sizeof (string), ...); - LighFusion
  • @gbg sizeof does not apply to variables of type String? Your comment is not appropriate here, if a person needs to transfer a string to a buffer - the decision is quite tolerable, and instead of condemning you would give your example, and I do not think that it would be very different from mine. In my opinion, this is not a "C ++ Masters" contest, which I know, I share, and you are splitting up a clown. - LighFusion
  • @LighFusion sizeof () does not work this way. Go read the standard and do not give the wrong advice, so as not to occupy the time of the author of the question. To find out the length of a string, you need to use string.length (). - gbg
  • Thanks for the replies, using c_str () helped. Yes, I'm sorry that I didn’t unsubscribe, I just forgot the problem the next day, but I forgot about this topic. Here is a piece of working code: Char buf[1019]; String str = Form1->Edit1->Text; for(int i=0; i<str.Length(); i++) buf[i] = str.c_str()[i]; Char buf[1019]; String str = Form1->Edit1->Text; for(int i=0; i<str.Length(); i++) buf[i] = str.c_str()[i]; - WFZ

1 answer 1

Thanks for the replies, using c_str () helped. Yes, I'm sorry that I didn’t unsubscribe, I just forgot the problem the next day, but I forgot about this topic. Here is a piece of working code:

 Char buf[1019]; String str = Form1->Edit1->Text; for(int i=0; i<str.Length(); i++) buf[i] = str.c_str()[i];