SpykeRel04D
SpykeRel04D

Reputation: 47

Garbage printing in string convert from Streambuffer

I'm making a simulator of C++ Client/Server TCP using Boost::Asio library.

Here is part of my code:

Client:

std::string option;
std::getline(std::cin, option);
option.push_back('\r');
option.push_back('\n');
boost::asio::write(client_socket, boost::asio::buffer(option));

Server:

boost::asio::streambuf received;
boost::asio::read_until(socket, received, "\r\n");
char number[7];
recieved.sgetn(number, 7);
std::cout << "The entered number is: " << number << std::endl;

(I included only the problematic code)

My problem is garbage values are included in the char[] number, like this for input 1234567:

enter image description here

How can I fix this issue?

Upvotes: 1

Views: 158

Answers (2)

LPs
LPs

Reputation: 16223

char number[8];

recieved.sgetn(number, 7);

number[7] = '\0'

Upvotes: 1

Dinal24
Dinal24

Reputation: 3192

You have to null terminate your string, which is not done by you.

char number[7]; //you need additional allocation for '\0'

use

char number[8];

Upvotes: 6

Related Questions