Is there any way I can get c[4] or c[3] by using data?Code:
char c[6]={"hello"};
void* data;
data=c;
I tried cout<< (char*)data[4]; but it doesnt work.
Printable View
Is there any way I can get c[4] or c[3] by using data?Code:
char c[6]={"hello"};
void* data;
data=c;
I tried cout<< (char*)data[4]; but it doesnt work.
You need to convert the void pointer back to an appropriate type (char *), BEFORE trying to dereference it.
or (if you don't want to add another variable)Code:char *cdata = (char *)data;
cout << cdata[4];
The extra brackets I have in this line (which you do not) are important: your code and mine mean different things.Code:cout << ((char *)data)[4];
Thx it works but it doesnt at the same time.
I have this
is there any way I can pass c[0] to the function display?Code:
display(const char *str){
cout <<str;}
at first, I couldnt pass c[0] or c[1] because they are const char so I thought it would work if I pass in a pointer.
after use your code, I tried to call display
display(((char *)data)[4]);
it didnt work.
I need something to convert a constant char to a string :(----> dam it, convert to string doesnt work lol
What is c?
oh it continues with the code I have in the 1st post.
Code:char c[6]={"hello"};
Ah. If you want to print a character, then print it. There's no need to try and force it to be printed as a null terminated string.
well I wish it could be done that easily.
This is a part of my assignment.
The display function is already in used to print a null terminated string.
I cant modify the display function.
I cant use cout<< either. I must use that display function :(
Don't modify it then. Just don't use it.
The display function isnt that simple. There are other parameters that I didnt mention here.
I need to use that display function to display something like
(hello world)
where
hello world is the null terminated string
( ) are store in a char c[3];
c[3] could hold anything, [], //...
w/o using the display function, no way I can get them to display together unless I write an overload function for display which I am not allowed to.
I can call display("(") w/o any problem but the thing is that it is not always a "(".
You could modify the null terminated string to prepend '(' and append ')'. Or you could std::cout << '('; call this function, then std::cout << ')';
could you tell me more on how can I prepend '(' to a null terminated string?
thanks :)
There are a few ways, e.g.,Quote:
Originally Posted by byebyebyezzz
Code:stringstream ss;
ss << c[0] << str << c[1];
std::strcpy(str, ss.str().c_str()); // assume enough space for strcpy
well this what I did and it worked
char s[2]
s[0] = c[0];
s[1] = '\0';
I wouldnt come up with that w/o you
thanks