CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Sep 2004
    Posts
    21

    How to convert string variable to char array

    Code:
    string myStrArray[10];
     
    for(int i = 0; i < 10; ++i)
    {
    	myStrArray[i] = "a";
    }
     
    string myString;
    cin>>myString; // input myString = "a"
     
    char charStr1[] = myStrArray[0];
    char charStr2[] = myString;
     
    if(strcmp(charStr1, charStr2) == 0)
    	cout<<"Same!!!";
    When I try the code above, it was an error. I have already changed the string variable to char array, but somehow it still does not work.

    Any help would much be appriciated.
    hl

  2. #2
    Join Date
    Aug 2005
    Posts
    478

    Re: How to convert string variable to char array

    http://www.msoe.edu/eecs/cese/resources/stl/string.htm
    Check out the string::c_str() member. But why strcmp() when the == operator is overloaded to compare string objects?

  3. #3
    Join Date
    Feb 2003
    Posts
    377

    Re: How to convert string variable to char array

    When calling functions that require a const char*, the c_str() method is the way to go. Usually there is an equivalent for C++ strings (as Calculator mentioned), so you don't have to do that at all. In this case the string class has operator== overloaded and a compare() method as well.

    If you need a non-const character array, you'll need to use strcpy to copy the string's contents into a new character array that you've allocated memory for. Since strcpy takes a const char* for the source, you would of course need to use the c_str() method there.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured