Solved

String function

Posted on 2001-07-03
44
297 Views
Last Modified: 2010-05-18
Hi

I have a string like that
"String1 /n String2 /n " ...

I wanna do some sort of trick, a function that takes the string above and puts the strings into strings like this

char str1[100] String1;
char str2[100] String2;

So what I need it to look for the "/n" shift line, evry time there is a shift line, the following of the string shall be put into another buffer..

How is that done, is there some sort of C function that chan do the trick ?

CB.

0
Comment
Question by:win32
  • 21
  • 12
  • 7
  • +2
44 Comments
 
LVL 22

Expert Comment

by:nietod
Comment Utility
The easiest solution is to place the data into a stringstream object, then read lines out of it.  Like

char Str1[100];    // I woudl recommend that you don't use
char Str2[100];   // character arrays here.  String objects would
                              // be better!!!!

string S1 = "this is string 1 \n this is string 2 \n this is string 3";
stringstream StrStm;

StrStm(S1); // Store the multiline string in the stream.

string Lin;

getline(StrStm,Lin); // Copy a line into Lin.
strcpy(Str1,Lin.c_str()); // Copy line into your character array.
                  // note that this woudl be much better if you didn't
                  // use a character array but used a string object instead.

0
 
LVL 22

Expert Comment

by:nietod
Comment Utility
In C++ its usually unwise to use character arrays for storing strings.  They are not very powerful.  Worse, they are very dangerious.  You can easily make mistakes with them that will cause yoru program to crash.  For example, what if the lines in the string are longer than 99 charcters?  If so the strings will overflow those character arrays and corrupt other memory uised byt he program.  This can cause irratic behavior and crashes.  Instead, you should be using string objects.  Like

string Str1;
string Str2;

string S1 = "this is string 1 \n this is string 2 \n this is string 3";
stringstream StrStm;

StrStm.str(S1); // OPPS.  I had this line wrong above.
                             // note that the data string, S1, is passed
                             // to the str() member function of the stream.

getline(StrStm,Str1);  // Get 1st line.
getline(StrStm,Str2);  // Get 2nd line.


0
 
LVL 1

Expert Comment

by:glebspy
Comment Utility
First, do you mean \n rather than /n? I assume so.

I hope it is ok if I give the answer in c++.

#include<string>
#include<iostream>

//If microsoft
using namespace std

string*split_String(const string&s){
 if(s.size()==0)return NULL;

 int number_Of_Shifts=0;
 for(int i=0;i<s.size()-1;i++)
  if(s[i]=='\n')number_Of_Shifts++;

 string*A=new string[number_Of_Shifts+1];

 int current_String=0;
 for(int i=0;i<s.size()-1;i++){
  if(s[i]=='\n')current_String++;
  else A[current_String]+=s[i];}

 return A;}

//Example of use:

void main(void){
 string to_Split=
  string("One\nTwo\nThree\n");
 string*splitted_Strings=split_String(to_Split);

 cout<<splitted_Strings[0]<<endl
     <<splitted_Strings[1]<<endl
     <<splitted_Strings[2]<<endl;

 delete[]splitted_Strings;
}
0
 
LVL 1

Expert Comment

by:glebspy
Comment Utility
Sorry for the accident nietod, it's all yours.
0
 

Author Comment

by:win32
Comment Utility
Sure man, buf if you for some reson have that string, what can you do about it ?

If it's your input str, and you need to do the split !
0
 
LVL 22

Accepted Solution

by:
nietod earned 50 total points
Comment Utility
>>  buf if you for some reson have that string, what can you do about it ?
There is almost never a good reason to use charcter arrays.  Bit if you have to then use them.  The first example I posted does that.

>> it's your input str, and you need to do the split !
Simple convert the input to a string object.  Its very easy.


i.e.

#incude <sstream>
#include string>
#include <string.h>

using namespace std;

int main()
{
   char Str1[100];    
   char Str2[100];  
   char Str3[100];  

   char Data[] = "this is string 1 \n this is string 2 \n this is string 3";
   string S1 = Data; // This converts the character array to a string object.

   stringstream StrStm;

   StrStm.str(S1); // Store the multiline string in the stream.

   string Lin;

   getline(StrStm,Lin); // Copy a line into Lin.
   strcpy(Str1,Lin.c_str()); // Copy line into your character array.
   getline(StrStm,Lin); // Copy a line into Lin.
   strcpy(Str2,Lin.c_str()); // Copy line into your character array.
   getline(StrStm,Lin); // Copy a line into Lin.
   strcpy(Str3,Lin.c_str()); // Copy line into your character array.

   return 0;
}


Now if you have quesitons, you can ask them.  You do not need to reject my answer if you only have questiosn about it.
0
 
LVL 30

Expert Comment

by:Axter
Comment Utility
win32,
Do you want a C answer or a C++ answer?
0
 
LVL 30

Expert Comment

by:Axter
Comment Utility
Here's a class that should do what you're looking for:

template<class TYPE>
class StringParseToPOD
{
public:
     StringParseToPOD(const char *psz_data, char *seps = "\n")
     {
          char *szString = new char[strlen(psz_data)+1];
          strcpy(szString,psz_data);
          int Qty = sizeof(POD) / sizeof(POD[0]);
          int Len = sizeof(POD) / Qty;
          memset(POD,0,sizeof(POD));
          char *token = strtok(szString, seps);
          for (int d = 0;((token != NULL) && (d < Qty));d++)
          {
               strncpy(POD[d],token,Len-1);
               token = strtok( NULL, seps );
          }
     };
   operator TYPE&()
   {
        return POD;
   }
   TYPE POD;
};
0
 
LVL 30

Expert Comment

by:Axter
Comment Utility
Example Implementation:

int main(int argc, char* argv[])
{
char *sz_data = "test for str1 \ntest for str2 \ntest for str3";
char asz_data[3][20];
memcpy(asz_data,(StringParseToPOD<char [3][20]>)sz_data,sizeof(asz_data));
return 0;
}


Hi (win32):
Feel free to click the [Reject Answer] button near (Answer-poster's) response, if you're not satisfied with the current answer.
Doing so will increase your chance of obtaining additional input from other experts.  Later, you can click the [Select Comment as Answer] button on any response.
0
 
LVL 30

Expert Comment

by:Axter
Comment Utility
FYI,
In the above class, if there are more "\n" return characters then index strings, the remaining string is discarded.

Example:
int main(int argc, char* argv[])
{
char *sz_datax = "test for str1 \ntest for str2 \ntest for str3";
char asz_datax1[2][20];
char asz_datax2[3][20];
char asz_datax3[4][20];
memcpy(asz_datax1,(StringParseToPOD<char [2][20]>)sz_datax,sizeof(asz_datax1));
memcpy(asz_datax2,(StringParseToPOD<char [3][20]>)sz_datax,sizeof(asz_datax2));
memcpy(asz_datax3,(StringParseToPOD<char [4][20]>)sz_datax,sizeof(asz_datax3));
return 0;
}

0
 
LVL 30

Expert Comment

by:Axter
Comment Utility
The following class will let you convert to a vector<string> variable:

#include <string>
#include <vector>
class StrParse2VectStr
{
   std::vector<std::string> m_StringList;
public:
     StrParse2VectStr(const char *psz_data, char *seps = "\n")
     {
          char *szString = new char[strlen(psz_data)+1];
          strcpy(szString,psz_data);
          char *token = strtok(szString, seps);
          for (int d = 0;token != NULL;d++)
          {
               m_StringList.push_back(token);
               token = strtok( NULL, seps );
          }
     };
     operator const std::vector<std::string>&()
     {
          return m_StringList;
     }
};

Example code:
char *sz_datax = "test for str1 \ntest for str2 \ntest for str3";
std::vector<std::string> StringList = StrParse2VectStr(sz_datax);
const char *test1 = StringList[0].c_str();
const char *test2 = StringList[1].c_str();
const char *test3 = StringList[2].c_str();
0
 
LVL 30

Expert Comment

by:Axter
Comment Utility
Correction on above class:

class StrParse2VectStr
{
   std::vector<std::string> m_StringList;
public:
     StrParse2VectStr(const char *psz_data, char *seps = "\n")
     {
          char *szString = new char[strlen(psz_data)+1];
          strcpy(szString,psz_data);
          char *token = strtok(szString, seps);
          while(token != NULL)
          {
               m_StringList.push_back(token);
               token = strtok(NULL, seps);
          }
     };
     operator const std::vector<std::string>&()
     {
          return m_StringList;
     }
};
0
 
LVL 22

Expert Comment

by:nietod
Comment Utility
Isn't that a lot of work when there are built-in STL features to do the exact same thing?
0
 
LVL 30

Expert Comment

by:Axter
Comment Utility
>>Isn't that a lot of work when there are built-in STL
>>features to do the exact same thing?
Please explain.
0
 
LVL 30

Expert Comment

by:Axter
Comment Utility
nietod,
Maybe I'm misunderstanding the question, but as I read it, the questioner is asking how to parse a single string into a string array.

char *sz_datax = "test for str1 \ntest for str2 \ntest for str3";
char asz_datax1[3][20];

So if you have the above variables, he/she wants a method to parse sz_datax into asz_datax1.

I didn't see this in your example, and I'm not familiar with any built-in STL feature that can do this.
Can you show an example of what you're referring to?

With the method I posted, the following is the only work that is required in questioners code (other then the class):

memcpy(asz_datax1,(StringParseToPOD<char [3][20]>)sz_datax,sizeof(asz_datax1));

I think a one line statement is hardly any work, but if you have a shorter method, please post it.
0
 
LVL 22

Expert Comment

by:nietod
Comment Utility
>>  didn't see this in your example, and I'm not familiar with any built-in STL feature that can do this.
You could easily miss it.  My complete working example is a fraction of the size of your code.  The solution part is really about 3 lines.

>> I'm not familiar with any built-in STL feature that can do this.
That suggests you should read and understand my example, before posting your own.  That way, you won't give any false impressiosn that you solution is better.

>>  the only work that is required in questioners code
Plus all the code you wrote!    Code that has some questionable practices.

I my method all that is needed is.  to fill a stream object with the data--no coding of clases there, its built-in, then either 1 or 2 statement to extract each line--all done through standard means, no parsing required.

>> if you have a shorter method, please post it.
I did.
0
 
LVL 1

Expert Comment

by:CSLIU
Comment Utility
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
    char string[] = "String1 \n String2 \n";
    char seps[]   = " \n";
    char *token;
    char tk_array[10][100];
    int  i=0,j;

   /* Establish string and get the first token: */
   token = strtok( string, seps );
   while( token != NULL )
   {
      /* While there are tokens in "string" */
      strcpy( tk_array[i],token );
      /* Get next token: */
      token = strtok( NULL, seps );
      i++;
   }

   for( j = 0; j < i; j++ )
       printf("%s\n" tk_array[j] );

   return 0;
}
0
 
LVL 1

Expert Comment

by:CSLIU
Comment Utility
0
 
LVL 1

Expert Comment

by:CSLIU
Comment Utility
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    char string[] = "String1 \n String2 \n";
    char str1[100],str2[100];

    sscanf( string, "%s\n%s\n", str1, str2 );

    printf("%s, %s", str1, str2 );
    return 0;
}
0
 
LVL 1

Expert Comment

by:CSLIU
Comment Utility
Axter answered your question.
0
 
LVL 22

Expert Comment

by:nietod
Comment Utility
>> Axter answered your question.
Did you miss my solution or do you not understand it?.  its hard to imagine any support for a complex solution over a simple one.
0
 
LVL 1

Expert Comment

by:CSLIU
Comment Utility
>> Axter answered your question.
>Did you miss my solution or do you not understand it?.  >its hard to imagine any support for a complex
>solution over a simple one.

You answered , too.
But i like his answer.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 30

Expert Comment

by:Axter
Comment Utility
>>Did you miss my solution or do you not understand it?.  
>>its hard to imagine any support for a complex
>>solution over a simple one.
I don' believe that your posted solution is what the questioner is asking for.
The questioner is asking for a function that can perform the transfer.  You did not post a function, you posted the code required to do it, but not a single function method.

If the questioner needs to do this in multiple locations, your method would require more work.
I feel my method is more practical, and the StrParse2VectStr uses better methods, and it is much more efficient then the method you posted.
0
 
LVL 1

Expert Comment

by:CSLIU
Comment Utility
>> Axter answered your question.
>Did you miss my solution or do you not understand it?.  >its hard to imagine any support for a complex
>solution over a simple one.

You answered , too.
But i like his answer.
0
 
LVL 30

Expert Comment

by:Axter
Comment Utility
>>You could easily miss it.  My complete working example
>>is a fraction of the size of your code.  The
>>solution part is really about 3 lines.

I don't see a 3 line solution.  Your solution looks like it's a lot more work then the one I posted.

>>That suggests you should read and understand my example,
>>before posting your own.  That way, you won't
>>give any false impressiosn that you solution is better.

I did read your solution, and that's why I posted my solution.  I don't feel you gave an adequate method.  It has poor optimization and I don't think it addresses the questioner's needs.
I think you should read the solution I posted again, that way you won't give any false impression that your solution is better.
0
 
LVL 1

Expert Comment

by:CSLIU
Comment Utility
>> Axter answered your question.
>Did you miss my solution or do you not understand it?.  >its hard to imagine any support for a complex
>solution over a simple one.

You answered , too.
But i like his answer.
0
 
LVL 30

Expert Comment

by:Axter
Comment Utility
nietod
>>>> if you have a shorter method, please post it.
>>I did.

You didn't.  The questioner didn't ask how to parse a string into an array.  The questioner asked for a function that can do it.
That's  two different thing.
You have not posted any function.  What you have posted is the code for parsing a string with questionable methods.
0
 
LVL 22

Expert Comment

by:nietod
Comment Utility
>> The questioner is asking for a function that can perform the
>> transfer.  You did not post a function,
The "jeparty" trick.  Sorry your response must be in the form of a question?

No my solution is not in the form of a function.  But the quesiton doens't askl for a function, its just looking for a solution.  I don't know why you feel it has to be a function.   Its almost painful to make it a function as that is so unnecessary for such a simple answer.  But here goes

#incude <sstream>
#include string>
#include <string.h>

using namespace std;

void GetLine(char *Dst,istream &S)
{
   string Lin;

   getline(S,Lin); // Copy a line into Lin.
   strcpy(Dst,Lin.c_str()); // Copy line into your character array.
}

int main()
{
   char Str1[100];    
   char Str2[100];  
   char Str3[100];  

   char Data[] = "this is string 1 \n this is string 2 \n this is string 3";

   stringstream StrStm;

   StrStm.str(Data); // Store the multiline string in the stream.

   GetLine(Str1,StrStm);
   GetLine(Str2,StrStm);
   GetLine(Str3,StrStm);
   return 0;
}

So now its a function.   Doesn't seem to be that signifcant a change.  

The solution is still veyr simple, very efficient, very elegant, and very easy to write.   It is very safe except for the fact that the data is ultimately copied to a character array, it could crash there, but that is one of the--unfortuante--restrictions of the question, not a flaw with the answer.

On the other hand, your solution is complex, has  memory leaks,  memsets a template parameter type (unsafe), and has unused variables.  its hard to image why you think it might be superior.

>> But i like his answer.
Can you be more specific?  What exactly do you like about it?  What do you dislike about mine?

Does the memory leak have any influence on your decission?   what abotu using memset() on a template parameter, one that might not be a POD type?   Do you like the for loop?  i.e. is that a good way to code a loop with those requirements?  Is it efficient?

On the other hand, does my code seem to complex to you?  why?  Does it seem efficeient?  Yes? No?  Why?  Does it work?  Why or Why not?  
0
 
LVL 30

Expert Comment

by:Axter
Comment Utility
>>has  memory leaks
I see no memory leaks in my solution.
If you can't point to the memory leak, then you shouldn't say that it has a memory leak.

>>has unused variables.  
That leads me to believe you don't understand the code.  You should first study the code, then ask questions if you don't understand it.
If you still don't understand the code, then you should not make any comments on it until you do.

>>hat abotu using memset() on a template
>>parameter, one that might not be a POD type?  
The method is for a char array.  The memset is safe the way it's used.  If you think it is not, then you don't understand memset.
0
 
LVL 30

Expert Comment

by:Axter
Comment Utility
nietod,
Your solution is moving the data in multiple variables.
My solution is not.
Although the questioner did ask for a multiple variable solution, I believe that a single string array variable is much more practical.
You can do a lot more with the following:
char mystr[3][100];

Then you can with the following multiple variables:
char str1[100];
char str2[100];
char str3[100];

So I think the correct approach is to have a single array string, and parse the data into it, in one shot.

I don't think having multiple variables, and then parsing the data variable, by variable, is very practical.
It's bad design with little flexibility.

If you want to recommend this bad design to the user, you are free to do so.
0
 
LVL 22

Expert Comment

by:nietod
Comment Utility
I have no reason to make things up!

>>  char *szString = new char[strlen(psz_data)+1];
When do you delete this memory?

>> >>has unused variables.  
>> That leads me to believe you don't understand the code.
>>         for (int d = 0;token != NULL;d++)

What is "d" for?  It looks like you even foudn that later and fixed it.  

>> StringParseToPOD(const char *psz_data, char *seps = "\n")
There is a syntax error there too.  Did you catch it?

the type of a string literal is "const char *const".  That will not compile on conforming compilers.   In fact, I don't think that compiles on VC?  

>> The memset is safe the way it's used.  If you think it is not, then
>> you don't understand memset.
So you made it a template that works with one data type.?  That is a little strange  don't you think?   Not really a template if only one tamplate parameter is possible.  And don't suggest that it works with both ASCII and wide characters, it only works with ASCII.  Its safe for one data type and will fail to compile or will compile but will fail to work correctly with other data types . Ever notice that STL doesn't use memset() on its parameter types.  Good templates don't.  That is what traits are for.  They allow you to write templates that safely act as templates.

>> If you still don't understand the code
I think I've prooved I've understood it.  But do you?  
0
 
LVL 22

Expert Comment

by:nietod
Comment Utility
>> Although the questioner did ask for a multiple variable solution, I believe that a
>> single string array variable is much more practical.
And that is impossible to do with my soluiton too!!!. darn.  Oh wait no, its not impossible, its triivial.

You;ve got

int main()
{
   char StrAray[3][100];    

   char Data[] = "this is string 1 \n this is string 2 \n this is string 3";

   stringstream StrStm;

    StrStm.str(Data); // Store the multiline string in the stream.

    GetLine(StrArray[0],StrStm);
    GetLine(StrArray[2],StrStm);
    GetLine(StrArray[3],StrStm);

   return 0;
}

Or if you want to get really fancy and support any number of lines, then

void GetLine(string &Dst,istream &S)
{
    getline(S,Dst); // Copy a line into Lin. // A one line function to not break
                                                // the answer must be a function rule.
}

int main()
{
   vector<stirng> A;

   char Data[] = "this is string 1 \n this is string 2 \n this is string 3";

   stringstream StrStm;

    StrStm.str(Data); // Store the multiline string in the stream.

   while (!StrStm.eof())  
   {
       string Lin;
       GetLine(Lin,StrStm);
       A.push_back(Lin);
   }
   return 0;
}

I hope this looks very simple to you!
0
 
LVL 22

Expert Comment

by:nietod
Comment Utility
>> f you want to recommend this bad design to the user, you are free to do so.
Yo don;t knw what this is for.   If the data contains someones address, then it might be desirable to break it into sepreate, unrelated varables.   i.e. a name might be one varaible and the street address might be another etc etc.   If the lines are all different instances of the same thing (like items in a shopping list), then it might make sense to place the data in an  single array or vector.   but I did not recommend either solution, that was not posed in the question or suggested in my answer.  The technique I proposed works extremely well for either.  
0
 
LVL 30

Expert Comment

by:Axter
Comment Utility
nietod,
Since you don't seem to understand memset, I'll see if I can explain it to you.

template<class TYPE>
class foo
{
public:
foo()
{
 TYPE x;
 memset(x,0,sizeof(x));
}
};


With the above template foo class, it will not allow you to use an unsafe class type that requires & in front of it.
If you tried to do someting like the following:

class foofoo
{
public:
int xx;
int xxx;
};

foo<foofoo> x;

The above line will not compile.  So you can not use an unsafe type with memset the way it is used in foo.  This makes it type safe.

When you use a safe type with memset, it will not go beyound the length of the variable, because of the sizeof() function used in foo.

If you have anymore questions, feel free to ask.
0
 
LVL 30

Expert Comment

by:Axter
Comment Utility
>>When do you delete this memory?
You should have stated that in the first place instead of making an abstract statement.
You have a bad habit of not backing up you statments with data.
Back it up, or don't say it at all.
0
 
LVL 30

Expert Comment

by:Axter
Comment Utility
>>What is "d" for?  It looks like you even foudn that
>>later and fixed it.  
It was fixed in the very next comment a 5 minutes later.

So either you new this already, and you posted your comment knowing that you where posting false information.  This would make you a liar.

Or you failed to read all the comments before posting false information, in which case I would say you need to completely read all the comments before posting remarks about other expert's code.  Failure to do so is bad etiquette.
0
 
LVL 30

Expert Comment

by:Axter
Comment Utility
>>the type of a string literal is "const char *const".  
>>That will not compile on conforming compilers.
>>  In fact, I don't think that compiles on VC?  
Of course that will compile.  I suggest you test things out before giving advise to questioners.
0
 
LVL 30

Expert Comment

by:Axter
Comment Utility
>>So you made it a template that works with one data
>>type.?  That is a little strange  don't you think?

I'm sure you would think that since you don't understand the code.

>>I think I've prooved I've understood it.  But do you?  
With the above statement, I think you have proven that you don't understand it.

>>And that is impossible to do with my soluiton too!!!.
>>darn.  Oh wait no, its not impossible, its triivial.
Will it's not currently possible to do with your function in on line.
It takes more work to do it with your code.
//*****************************
stringstream StrStm;
StrStm.str(Data);
GetLine(StrArray[0],StrStm);
GetLine(StrArray[2],StrStm);
GetLine(StrArray[3],StrStm);
//*****************************

That's a lot more work then what is required in my code.
My method only needs one line.

And what you call "fansy" looks like more bad code that needs more work.

>>The technique I proposed works extremely well for
>>either.    
I'm sure you think so, but I disagree.
0
 
LVL 30

Expert Comment

by:Axter
Comment Utility
Here's an update to the StringParseToPOD class.
I added a copy function to it.

template<class TYPE>
class StringParseToPOD
{
public:
    StringParseToPOD(const char *psz_data, char *seps = "\n")
    {
          char *szString = new char[strlen(psz_data)+1];
          strcpy(szString,psz_data);
          int Qty = sizeof(POD) / sizeof(POD[0]);
          int Len = sizeof(POD) / Qty;
          memset(POD,0,sizeof(POD));
          char *token = strtok(szString, seps);
          for (int d = 0;((token != NULL) && (d < Qty));d++)
          {
               strncpy(POD[d],token,Len-1);
               token = strtok( NULL, seps );
          }
          delete szString;
    };
     void Copy(TYPE &dest)
     {
          int Qty = sizeof(POD) / sizeof(POD[0]);
          std::copy(POD[0],POD[Qty],dest[0]);
     }
     operator TYPE&()
     {
          return POD;
     }
     TYPE POD;
};
0
 
LVL 30

Expert Comment

by:Axter
Comment Utility
Example code for above function:

int main(int argc, char* argv[])
{
char *sz_datax = "test for str1 \ntest for str2 \ntest for str3";
char asz_datax1[2][20];
char asz_datax2[3][20];
char asz_datax3[4][20];

StringParseToPOD<char [2][20]>(sz_data).Copy(asz_datax1);
StringParseToPOD<char [3][20]>(sz_data).Copy(asz_datax2);
StringParseToPOD<char [4][20]>(sz_data).Copy(asz_datax3);
return 0;
}
0
 
LVL 30

Expert Comment

by:Axter
Comment Utility
Another example:

int main(int argc, char* argv[])
{
char *sz_datax = "test for str1 \ntest for str2 \ntest for str3";
char asz_datax1[2][100];
char asz_datax2[3][20];
char asz_datax3[4][200];

StringParseToPOD<char [2][100]>(sz_data).Copy(asz_datax1);
StringParseToPOD<char [3][20]>(sz_data).Copy(asz_datax2);
StringParseToPOD<char [4][200]>(sz_data).Copy(asz_datax3);
return 0;
}

You'll notice that the template class can work with different size arrays.

If you try to use an array size that does not match the destination variable, it will not compile.
This makes it type safe.  Much safer then the method posted by nietod.

In nietod's method the following code would be unsafe.
char StrAray[3][100];    
GetLine(StrArray[9],StrStm);

The template method is more type safe.  Better coding practice.
0
 
LVL 22

Expert Comment

by:nietod
Comment Utility
>> Since you don't seem to understand memset
Thanks for the tip!   Try memseting a string object, or a vector, or anything else.  

By placing a memset in your template, you have created a sitation where the template will corrupt memory if the template parameter types in not a POD type.  You actualy make this work in that the code won't compiler if the tempalte  parameter type is not a char.  In other words it the tempalte must be instaciated with only one data type--so in essence it is not a template.

>> The above line will not compile.  So you can not use an unsafe type
>> with memset the way it is used in foo.  This makes it type safe.
Yes it will.

>> You should have stated that in the first place instead of making an abstract statement.
>> You have a bad habit of not backing up you statments with data.
>> Back it up, or don't say it at all.
You have several examples where you allocate memory and fail to delete it.  Somehow this is my fault and makes your solution better than mine?

Your solution has a memory leak.  yes or no?

>> t was fixed in the very next comment a 5 minutes later.
In one of your solutions then better than the others?  What is the difference between them.  You've posted a ton of code and not explained if one is "the" solition and others not.  My assumption is that there are all variations that you are suggesting are supperior ot mine.  If not, you should make that clear.  

>> Or you failed to read all the comments before posting false information,
The false information being?  I mean you did have a memroy leak right--evne though that is my fault.  You do have an unused variable?  You do have a template that can only work with one data type?  You do have a string literal that is treated as non-constant.   I'm not making this stuff up.  its there.

I've read you comments.  You correct one post with another.  Does that correct all posts?  

>> Of course that will compile.
It is still a bug.   VC should prevent it.

>> I suggest you test things out before giving advise to questioners.
I told you it was a bug.  it is one.   I said I thought it would not compile under VC.  I didn't state I was sure of that.  

All your complaining doesn't change the fact that it is a bug..  Or make your memory leak go away etc.

>> 'm sure you would think that since you don't understand the code.
Try it.  it doesn't compile.  Even with wide character it doesn't work.   Try it.  How do you think the line

          strncpy(POD[d],token,Len-1);

will work if the template is created for any type other than char?

Does your code compile with other template data types?  Yes or no?

Now you;ve got another solutuon.  Does this superceed the others then?  

The new solution fixed one memory leak with another.  You've deleted an array with delete instead of delete [].

it can now be insanciated for arrays of POD types only.  Is that what you wanted?  

Is this really a superior solution?  why?  Doesn't it seem extremely complex?

0
 
LVL 22

Expert Comment

by:nietod
Comment Utility
>> In nietod's method the following code would be unsafe.
>> char StrAray[3][100];    
>> GetLine(StrArray[9],StrStm);
>>
>> The template method is more type safe.  Better coding practice.
That I agree is a flaw.  but it is a flaw in the question, not the solution.  As I said, orignally the best solution is t not use character arrays.  That is certanly the best solution to that.  

If you want to insure that the character array does not overflow, then that techniquye can easily be applied to the solution I presented.  The point is that my suggestion of how to parse the data is far far simpler.
0
 

Author Comment

by:win32
Comment Utility
That's a lot of work for 50pts, but I thank you for it, it is very usefull :-)
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now