Hello I have a small issue with my code here. I have a default UDP server program which initialises a character array to a size of 30.
The message is passed from the UDP client program to the UDP server program using the character array. When I try converting it to a string , it keeps priniting out these strange characters. Any advice how to get rid of them?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>
#include <iostream>
#include <sstream>
#include <string>
#include <stack>
#include <vector>
using namespace std;
//function declarations
void Convert(const string & Infix, string & Postfix);
bool IsOperand(char ch);
bool TakesPrecedence(char OperatorA, char OperatorB);
/*My functions I've added*/
string Change_me(string);
string Insert_comma(string);
bool Check_valid(string);
double Eval(string[]);
void Next(string);
#define BUFSIZE 30
void ErrorHandling(char *message);
int main(int argc, char **argv)
{
WSADATA wsaData;
SOCKET hServSock;
char message[BUFSIZE];
int strLen;
SOCKADDR_IN servAddr;
SOCKADDR_IN clntAddr;
int clntAddrSize;
if(argc!=2){
printf("Usage : %s <port>\n", argv[0]);
exit(1);
}
if(WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
ErrorHandling("WSAStartup() error!");
hServSock=socket(PF_INET, SOCK_DGRAM, 0);
if(hServSock == INVALID_SOCKET)
ErrorHandling("socket() error!");
memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family=AF_INET;
servAddr.sin_addr.s_addr=htonl(INADDR_ANY);
servAddr.sin_port=htons(atoi(argv[1]));
if(bind(hServSock, (SOCKADDR*) &servAddr, sizeof(servAddr))==SOCKET_ERROR)
ErrorHandling("bind() error");
while(1) {
string Postfix;
clntAddrSize=sizeof(clntAddr);
strLen = recvfrom(hServSock, message, BUFSIZE, 0, (SOCKADDR*)&clntAddr, &clntAddrSize);
//need help here how to convert char to the string
string Infix;// test ="(99*100+200)-10";
char*result;
result=message;
Infix=result;
printf("Test2 %s\n",message);// gibberish printed
If the message isn't null-terminated, %s can't format it. Try
printf("Test2 %.*s", strlen, message);
provided 'strlen' is non-negative of course. You aren't checking that either.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.