-
Array of Strings
All, I have a problem where my program just hangs on a certain line, and I can't figure out why.
It's a command line app where it reads in a file and based on the user's arguments to the program, it will split the file into X seperate files.
To do this I read each line of the file using getline and stuff it into a string (not char) using string.append(). As I'm reading the file, I'm filtering out
certain values based on user args and duplicate rows.
After I've read the file in, I want to split it into X seperate files. First, I define an Array of Strings using malloc:
Code:
string *aOutputFiles;
if ((aOutputFiles = (string *) malloc ( intTempNumberFiles * sizeof *aOutputFiles )) == NULL) {
cerr << "\nError! Not enough memory to allocate buffer\n";
exit(EXIT_FAILURE);
}
Then I proceed to loop thru the string finding each NewLine value and stuffing it into the String Array:
Code:
intIterator = 0;
//now split the input file into multiple pieces
if (strInputFileContents.length() > 0) {
szFind=strInputFileContents.find_first_of("\n");
while (szFind!=string::npos) {
aOutputFiles[intIterator].append(strInputFileContents,0,(szFind+1)); //<--this is the line that breaks
//but not all the time...and if it does it's usually on the 2nd iteration of the loop
strInputFileContents.erase(0,(szFind+1));
szFind=strInputFileContents.find_first_of("\n");
if ( intIterator >= (intTempNumberFiles - 1) ) {
intIterator = 0;
} else {
intIterator = intIterator + 1;
}
}
}
Any ideas?
Also, if there's a better/faster way to do this please let me know also...
Thanks,
Brad
-
I'm afraid that you can't allocate an array of strings with malloc. malloc just gives you enough memory for x strings, but it doesn't mean you'll have any actual usable string objects - that memory just contains garbage. The C++ equivalent of malloc that also constructs the object(s) is new/new[].
However, in C++ one would really just use a std::vector<std::string>.
Next, wouldn't it be simpler to read a line with getline and append it to a suitable string?
Technically, you could use string::find instead of find_first_of (which means find any of the given characters), and there's lots of expensive erasing going on (use a version of find that takes position to start search from + substr to extract lines?)
-
Many Thanks!
Anon,
Thank you for your advise & input!! It worked!!
I'm so used to using arrays in other languages, but vectors sure make things easier in C++.
Brad
-
Lists Too!!
Guys, after seeing what vectors could do for me, I looked at some of the other
containers that C++ had to offer and I found some neat features with lists.
They can sort easily and output unique values. This is great for my app!
Anon, you Rock!!
Many Thanks again!!
Brad
-
Vectors sort easily and can output unique values too (look at <algorithm> header, list only provides those as methods, because they can be implemented (more) efficiently if you have access to implementation details of a linked list).