#1
  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2002
    Location
    England
    Posts
    5
    Rep Power
    0

    C++ Pointers and Strings


    Help! :)

    What happens if I have the following code?

    PHP Code:
    charastring "Hello";
    cin >> astring
    If my knowledge of C++ pointers, and how they work are correct, that code assigns the address of the first character of "Hello" to the pointer. Then, the next line, takes a string from the user, and assigns the address of the first character of that string to the pointer?

    Right?
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jan 2002
    Location
    Seattle WA
    Posts
    863
    Rep Power
    14
    I don't think you can use a char* for cin, can you?
  4. #3
  5. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2002
    Location
    England
    Posts
    5
    Rep Power
    0
    You can't? Hmm :confused:
  6. #4
  7. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2001
    Location
    USA
    Posts
    286
    Rep Power
    14
    Why don't you use std::string?
    Jon Sagara

    "Me fail English? That's unpossible!"
  8. #5
  9. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2002
    Location
    South Carolina
    Posts
    0
    Rep Power
    0

    This may be too much information


    This should clear up how to use c strings and c++ strings
    Code:
    #include <iostream>
    #include <string>
    
    int main(){
       char * astring; //how you declare c strings
       astring = new char[strlen("Hello")+1]; // you must set the size plus the null byte '\0'
       strcpy(astring, "Hello"); // how things are copied into a c string
       cout << astring << endl; // Hello
       delete [] astring; // If you new you must delete; however delete comes first
       astring = new char[30]; // Test this by typing in way more then 30 characters
       cin >> astring;
       cout << astring << endl;
    }
    
    /*
    int main(){
       //With strings, it is much easier b/c you don't worry about memory
       // The trade off is speed; however, it is best to use strings anyway
       // Make sure you #include <string>
       string astring = "Hello";
       cout << astring << endl;
       cin >> astring;
       cout << astring << endl;
       //If you look at the new char[30], you witness a buffer overflow
       // Hackers will type in more characters then allowed to change other parameters
       // This is why I use strings!
    }
    */

IMN logo majestic logo threadwatch logo seochat tools logo