I've written a code reading csv file using fold expressions. The only thing that should be defined is columns types and file name:
template <typename ...T, std::size_t... Is>
void parseLineToTuple(std::tuple<T...>& empty, const std::string& line, std::index_sequence<Is...>)
{
std::stringstream ss(line);
(ss >> ... >> std::get<Is>(empty));
}
template <typename ... T>
std::vector<std::tuple<T...>> readTuples(const std::string& fileName)
{
std::vector<std::tuple<T...>> lines;
std::ifstream file(fileName);
if (file.is_open())
{
std::string line;
while (getline(file, line))
{
std::tuple<T...> empty;
parseLineToTuple(empty, line, std::make_index_sequence<sizeof...(T)>());
lines.push_back(empty);
}
}
return lines;
}
To use it:
auto content = readTuples<std::string, int, double>("lines.csv");
lines.csv:
apple, 20, 10.54
orange, 30, 4.5
Is it possible to get index sequence another way than passing it to a method and get the received parameter type? If so I would get rid of the parseLineToTuple method
-
1\$\begingroup\$ I have rolled back Rev 2 → 1. Please see What to do when someone answers. \$\endgroup\$Sᴀᴍ Onᴇᴌᴀ– Sᴀᴍ Onᴇᴌᴀ ♦2022年10月17日 16:40:16 +00:00Commented Oct 17, 2022 at 16:40
1 Answer 1
There seems to be no way to determine whether the function succeeded or not. Callers can't even inspect the the input stream afterwards, because it's local to the function.
If it's supposed to throw an exception when open()
, getline()
or >>
fails, then we need to add
file.exceptions(std::ifstream::failbit|std::ifstream::badbit);
We'll need to do that between creating the stream and opening the file:
std::ifstream file();
file.exceptions(std::ifstream::failbit|std::ifstream::badbit);
if (!file.open(fileName)) {
throw std::ios_base::failure("open");
}