Hello!
I am working on the below program right now. I am asked to convert a string of words to char array. The libraries included are the only few that I can use. Since main function can not be altered, I have to return an allocated double pointer char array to match the 'free'. Basically, I need helps on the function called "words_array". Thank you guys so much for any helps.
#include <iostream>
#include <fstream>
#include <sstream>
#include <string.h>//<cstring>
#include <cstdlib>
/**
* Find number of words in s.
* @param count number of words in s (separated by a space)
* @param sstream a string stream object
* @param l a string that reads strings from stringstream
* return number of words in string s
*/
int words_of(std::string s) {
int count = 0;
std::string l;
std::stringstream sstream(s);
while (sstream >> l) ++count;
return count;
}
/**
* Convert string to character array of words.
* @param s string to convert
* @return jagged array of words
*/
char **word_array(std::string s) {
constchar *array = s.c_str();
char **charArray = (char**) malloc (sizeof(char) * (words_of(s)));
strncpy(*charArray, array, sizeof(charArray));
return charArray;
}
int main() {
std::string files = "architecture.txt boolean.txt computers.txt kitties.txt";
char **filenames = word_array(files);
int n = words_of(files);
for (int i=0; i<n; i++) {
std::ofstream outfile(filenames[i]);
outfile << "This is file " << i << std::endl;
free(filenames[i]);
}
free(filenames);
return 0;
}