Thread: I thought a string could hold an infinite number of characters?

  1. #16
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    And secondly i could do that with character arrays. With maybe 1 or 2 extra lines of code:
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
         char combined[5];
         char arrayA[25]="Hello ";
         char arrayB[25]="World!";
    
         strcat(combined, arrayA);
         strcat(combined, arrayB);
    
         cout<<combined<<endl;
    
         return 0;
    }
    ...which is a program that crashes, proving the point that the string type is much easier to use. In addition, strings are more secure when getting user input. Using char arrays for user input poses a security risk because a hacker can play around with memory that is out of bounds of the declared char array.
    Last edited by 7stud; 11-29-2005 at 07:30 PM.

  2. #17
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Junior89, your for loop using ^ on the string characters should work fine. Instead of going to 50, you should loop until the size of the smaller string, though. Otherwise you run off the end of the string and cause a crash (same would happen for character arrays).

  3. #18
    Registered User
    Join Date
    Nov 2004
    Location
    Pennsylvania
    Posts
    434
    Thanks again daved, youve been really helpful.

    7Stud - The program worked fine for me. I dont know what kind of computer your running but it should work fine. Throw in a cin.get() at the end. And you may need to throw in a combined[0]='\0' after the combined char array is declared. It does work fine. Just like the string one.

  4. #19
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    7stud is right. That program invokes undefined behavior and will often cause a crash. The combined array is not big enough to hold the other two strings concatenated together.

    The C++ string class is easier to use than C style arrays just by the fact that it is harder to mess up.

  5. #20
    Registered User
    Join Date
    Nov 2004
    Location
    Pennsylvania
    Posts
    434
    oh my bad with the combined thing, i missed a 0 after the 5. Whoops! Well strings certainly may be easier they never seemed to work for me which is why i always used/use char arrays. Perhaps ill be able to get strings down pat.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  2. Compile Error that i dont understand
    By bobthebullet990 in forum C++ Programming
    Replies: 5
    Last Post: 05-05-2006, 09:19 AM
  3. Something is wrong with this menu...
    By DarkViper in forum Windows Programming
    Replies: 2
    Last Post: 12-14-2002, 11:06 PM
  4. Replies: 2
    Last Post: 05-05-2002, 01:38 PM