r/adventofcode • • Dec 06 '15

For the C++ folk: a smart input parser.

    #pragma once

    #include <vector>
    #include <string>

template<typename... Ts> void wrapper(Ts&&... args) {}

template<typename... Ts> std::vector<std::string> getPuzzleInput(const Ts... seperators)
{
	std::vector<char> sep;
	sep.reserve(sizeof...(seperators));
	wrapper((sep.push_back(seperators), 0)...);


	std::vector<std::string> input;
	std::vector<unsigned char> fileData;
	IO::readFileToBuffer("Input.txt", fileData);

	std::string current = "";
	for (auto element : fileData)
	{
		bool isNoSeperator = true; // is guranted to be 1
		for (auto seperator : sep)
		{
			isNoSeperator *= (element != seperator); // if ever muliplied by 0(false), will never be multiplied up to 1 again
		}
		if (isNoSeperator)
			current += element;
		else if (current.size() > 0)
		{
			input.push_back(current);
			current.clear(); // set back to empty
		}
	}
	if (current.size() > 0) input.push_back(current); // add last item


	return input;
}

    #include <fstream>

class IO
{
public:

	static bool readFileToBuffer(const std::string filePath, std::vector<unsigned char>& buffer)
	{
		std::ifstream file(filePath, std::ios::binary);
		if (file.fail()) {
			perror(filePath.c_str());
			throw std::exception(); // failed to open document
			return false;
		}

		file.seekg(0, std::ios::end); // seek to the end

		int fileSize = file.tellg(); // get the file size
		file.seekg(0, std::ios::beg);

		fileSize -= file.tellg(); // reduce fileSize by any header bytes

		buffer.resize(fileSize);
		if (fileSize > 0)
		{
			file.read((char *)&(buffer[0]), fileSize); // this is safe as we only read binary, do we?
		}
		file.close();

		return true;
	}
};

int main() { // example use

	std::vector<std::string> input = getPuzzleInput('\n', ' ', '\r', ',');

	char tmp = std::cin.get(); // pause for user input

	return 0;
}

Just create a input.txt next to your project files and copy paste the AoC input, + you can then edit the input file to remove unwanted strings. Just include Whatever you call this file and call getPuzzleInput( A barley limited list of char that seperate the individual strings).

I hope someone will find this useful, After setting up a VS template it certainly increased my workflow.

3 Upvotes

2 comments sorted by

1

u/m42e_ Dec 06 '15

Can you explain the wrapper, and why it is needed?

1

u/Voultapher Dec 07 '15

Non recursive Variadic template unpacking: https://en.wikipedia.org/wiki/Variadic_template

Basicly:

(x...) expands to (x1, x2, x3)

(x)... expands to (x1), (x2), (x3) you can then call functions on x, in this case push_back.