By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,563 Members | 1,307 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,563 IT Pros & Developers. It's quick & easy.

convert char * to string object

P: 23
Hi please some one can help me. how to convert char * to string?

i have take char *argv[] from command line and want to pass to a function as string object(string str)
i want to first convert argv[1] to string object of type str, then pass to function().
please help me how to convert this
Nov 7 '08 #1
Share this Question
Share on Google+
3 Replies


100+
P: 424
A C string is a null-terminated character array. Thus, to convert your character array to a C string, simply append a null "\0" to the end of it. Note however that if your character array is in argv[1], then it will already be null-terminated because argv from main() is always an array of strings. If you want to use a C++ string, then simply declare one one passing the aforementioned C string to the constructor:
Expand|Select|Wrap|Line Numbers
  1. #include <string>
  2. int main(int argc, char * argv[])
  3. {
  4. std::string str(argv[1]); // str: C++ string containing the characters of argv[1]
  5. ...
  6.  
Nov 7 '08 #2

P: 23
A C string is a null-terminated character array. Thus, to convert your character array to a C string, simply append a null "\0" to the end of it. Note however that if your character array is in argv[1], then it will already be null-terminated because argv from main() is always an array of strings. If you want to use a C++ string, then simply declare one one passing the aforementioned C string to the constructor:
Expand|Select|Wrap|Line Numbers
  1. #include <string>
  2. int main(int argc, char * argv[])
  3. {
  4. std::string str(argv[1]); // str: C++ string containing the characters of argv[1]
  5. ...
  6.  
Thanks A lot.
can u tell me why the value of result is 3 at the time of debuging.
please see the below code for renameing afile i want to use rename() of stdio.h
const char *oldname=argv[1];
const char *newname="input.docx";
int result=rename(oldname,newname);
cout<<"result "<<result;
rename() return -1 ? not renamed please tell me why? there is no compiler error, but its not renaming
Nov 7 '08 #3

100+
P: 424
Just to check things are working as you expect, why not print out oldname to the terminal? Also, are you sure the file exists in the current path? note that if you use back slashes "\" they will need to be escaped: "\\".
Nov 7 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.