int to character array

How do I copy an integer into a character array in C/C++?

what do you mean?
You have an integer e.g. 234 and you want a char array (or string) "234"?

C++03:
1
2
3
4
5
int i = 234;
std::string str;
std::stringstream ss;
ss << i;
ss >> str;


C++11:
1
2
int i = 234;
std::string str = std::to_string(234);

Last edited on
All programming would be done in plain C. I don`t know C++.

Anyway, I mean

1
2
3
4
5
6
7
8
9
10
11

int getop (char s[]) {                 // Get next operator or numeric operand
      int i, c;

.....


 if (c == '-') {

 // Copy c to s
You did ask "in C/C++", so you did allow the C++ answers ...


A variable of type integer can hold a value that is in range [INT_MIN..INT_MAX]
A variable of type char can hold a value that is in range [CHAR_MIN..CHAR_MAX]
The first range is much larger than the first.

The '-' is a single character, but its numeric value (if ASCII coding base-10 is used) has more than one digit.


You have to be more specific about what you mean by "copy to array".
The standard way to convert int to string in C is with sprintf

1
2
3
int i = 368;
char str[15];
sprintf(str, "%d", i);


But your code fragment looks more than a bit vague, esp going by the first comment.

Andy

PS

@Gamer2015

Not sure about your C++03 code...

Do you mean?

1
2
3
4
int i = 234;
std::ostringstream ss;
str << i;
std::string str = ss.str();

Last edited on
Topic archived. No new replies allowed.