Thread: can you convert a char[] to a string

  1. #1
    Registered User
    Join Date
    Jun 2002
    Posts
    10

    can you convert a char[] to a string

    is it possible to convert a type string to a char[]?
    like
    string s;
    char[8] c;
    can you copy the contents of c into s?? i so how

  2. #2
    Registered User
    Join Date
    May 2002
    Posts
    317
    Code:
    #include<iostream>
    #include<string>
    
    using namespace std;
    
    int main(){
               char x[] = "aaaaaaaa";
               string s;
               for(int i=0;i<sizeof(x);i++)
                       s+=x[i];
    }

  3. #3
    Seeking motivation... endo's Avatar
    Join Date
    May 2002
    Posts
    537
    Not 100% definite on this but if I was going to write a string class, I would have a constructor to take care of that. You can probably do this:

    Code:
    char name[] = "endo";
    string s( name );

  4. #4
    Registered User
    Join Date
    May 2002
    Posts
    317
    Hey good, point, here this works with the string lib :

    Code:
    #include <iostream>
    #include <string>
    
    int main(){
    
               char x[] = "This is a test string";
               string s;
    
               s = string(x);  //type-caste to type string
    
               cout<<s;
               cin.get();
               return(0);
    }
    Just curious as to why considering a string is just a char array anyway? I mean why bother creating char x[] anyway?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. String Class
    By BKurosawa in forum C++ Programming
    Replies: 117
    Last Post: 08-09-2007, 01:02 AM
  2. can anyone see anything wrong with this code
    By occ0708 in forum C++ Programming
    Replies: 6
    Last Post: 12-07-2004, 12:47 PM
  3. Another overloading "<<" problem
    By alphaoide in forum C++ Programming
    Replies: 18
    Last Post: 09-30-2003, 10:32 AM
  4. ........ed off at functions
    By Klinerr1 in forum C++ Programming
    Replies: 8
    Last Post: 07-29-2002, 09:37 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM