0

how can we store int value in char* as representing character in c++.. for example, i want to store 10..char* p is a character pointer and i want to store 10 as character in that pointer...because i want to write iteration that generates character stream based on integer value.how to do char concatenation with integer(as char) with The similar java code be as:

for(int i=0; i<10; i++)
{
  string temp=value+i;//here i want to use char* to represent string in c++
  System.out.println(temp);
}
1
  • 3
    Use std::string instead of char*. It will make your life easier.
    – Fred Foo
    Jan 18, 2012 at 19:26

2 Answers 2

0

I know you said C++, but you also said char* so i am going to treat it as C. With C, you can't really do concatenation like that. The best way to do it would be to calculate the number of characters required, malloc that, then just store the characters in the char array. And remember to free it when you're done using it! In C, you have to do everything yourself!

1
  • or, malloc 11, and NULL terminate the string. Jan 18, 2012 at 19:53
0

I'm a little confused about what you're trying to do, but here's some information that I think will probably help you work it out:

  1. In C++, you should primarily use std::string to hold strings of characters.
  2. In regular C, the convention is to use a char* to hold a list of characters - these char*'s have to be null terminated ending in \0 so that your code knows where to stop printing the string of characters.
  3. Preferring the C++ way, you can concatenate strings with the + operator:

Here's an example:

std::string myString = "H";
myString += "e";
myString += "l";

std::cerr << myString;  //prints "Hel" to console.

You can also use a string stream which can mix data types:

std::stringstream ss;
ss << "h" << "e" << 7 << myCustomType << std::endl;

One other thing that's good to know is you can store an integer value in a char and it will work out the ascii representation when you print it.

For example:

char x = 65;  //x = capital A.
1
  • I think he wants to convert an int to a char*. So std::string tmp = (std::stringstream()<<value).str(); Jan 18, 2012 at 19:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.