garys
garys

Reputation: 139

How to create a char pointer in C++ that points to a concatenation of integers and commas?

Sorry if the terms are not right, just starting in C++ here... I have the following variables whose values can be 1 or 0 depending on another script result:

int number1, number2;

I need to format a variable as "X,Y" ending with a new line, so I did:

char c_number1 = '0' + number1; //going from int to char
char c_number2 = '0' + number2;
char comma = ',';
char new_line = '\n';
char concat_result[100] = {c_number1 + comma + c_number2 + new_line};

Here I don't get the expected result "X,Y" but a letter.

After that, I would need a pointer to that char variable, so I wrote:

const char *pointer_result = concat_result;

Not sure this is correct either.

Any guidance by any chance here?

Upvotes: 0

Views: 617

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 598134

Many different ways to handle this:

#include <string>

std::stream result = std::to_string(number1) + "," + std::to_string(number2) + "\n";
const char *pointer_result = result.c_str();
#include <sstream>
#include <string>

std::ostringstream oss;
oss << number1 << ',' << number2 << '\n';
std::string result = oss.str();
const char *pointer_result = result.c_str();
#include <cstdio>

char result[5];
std::sprintf(result, "%d,%d\n", number1, number2);
const char *pointer_result = result;

Upvotes: 1

MikeCAT
MikeCAT

Reputation: 75062

It seems you want to store each characters to separate elements of the array.

To archive that, use , instead of + to separate the elements.

char concat_result[100] = {c_number1, comma, c_number2, new_line};

This will initialize the first 4 elements with the specified characters and the other elements with zero.

Then you can use

const char *pointer_result = concat_result;

because most of arrays in expressions are converted to a pointer to the first element and assigning pointers without const to pointers having compatible types with const is allowed.

Upvotes: 1

Related Questions