0
\$\begingroup\$

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

Sᴀᴍ Onᴇᴌᴀ
29.5k16 gold badges45 silver badges201 bronze badges
asked Oct 17, 2022 at 13:30
\$\endgroup\$
1

1 Answer 1

1
\$\begingroup\$

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");
}
answered Oct 17, 2022 at 15:26
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.