In a question I answered I posted the following code:
#include <iostream>
#include <fstream>
#include <algorithm>
#include <sstream>
int main()
{
fstream iFile("names.txt", ios::in);
// This does not work so replacing with code that does
// iFile >> file;
// This is not the best way.
// But the closest to the intention of the original post.
// Get size of file.
ifile.seekg(0,std::ios::end);
std::streampos length = ifile.tellg();
ifile.seekg(0,std::ios::beg);
// Copy file into string.
std::string file(length, '\0');
ifile.read(&buffer[0],length);
// Original code continues.
std::istringstream ss(file);
std::string token;
std::vector<std::string> names;
while(std::getline(ss, token, ',')) {
names.push_back(token);
}
for (unsigned int i = 0; i < names.size(); i++) {
auto it = std::remove_if(names[i].begin(), names[i].end(), [&] (char c) { return c == '"'; });
names[i] = std::string(names[i].begin(), it);
}
for (unsigned int i = 0; i < names.size(); i++) {
std::cout << "names["<<i<<"]: " << names[i] << std::endl;
}
}
Would this be inefficient for larger files? Would it be better if I read the file into one string, did all the manipulation on that, and then put it into a vector?
main()
? You can't have free-floating code like that in C++. \$\endgroup\$iFile >> file;
that is not doing very much. It reads a single space separated word. So I am going to change that to read the whole file into a string. \$\endgroup\$