Connecting Tech Pros Worldwide Forums | Help | Site Map

convert char * to string object

Newbie
 
Join Date: Oct 2008
Posts: 23
#1: Nov 7 '08
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

Needs Regular Fix
 
Join Date: Sep 2007
Location: The Netherlands
Posts: 427
#2: Nov 7 '08

re: convert char * to string object


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.  
Newbie
 
Join Date: Oct 2008
Posts: 23
#3: Nov 7 '08

re: convert char * to string object


Quote:

Originally Posted by arnaudk

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
Needs Regular Fix
 
Join Date: Sep 2007
Location: The Netherlands
Posts: 427
#4: Nov 7 '08

re: convert char * to string object


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: "\\".
Reply