Skip to content

Instantly share code, notes, and snippets.

@JeroenDM
Created January 12, 2018 10:08
Show Gist options
  • Save JeroenDM/669caa9da6bc33356aa3ffec23a32564 to your computer and use it in GitHub Desktop.
Save JeroenDM/669caa9da6bc33356aa3ffec23a32564 to your computer and use it in GitHub Desktop.
I always forget how to read files with numbers in c++.
void read_file(std::string filename) {
// open file
std::ifstream infile(filename);
// check if opened succesfull
if (!infile) std::cout << "Failed to open file." << std::endl;
// read line by line and save in temporary string "line"
std::string line;
while(infile) {
getline(infile, line);
// the last line is an empty string apparantly
if (line != "") {
// use stringstream object to parse a single line
std::stringstream ss(line);
std::string temp;
std::cout << "reading a line" << std::endl;
while (getline(ss, temp, ',')) {
// convert to float and print
std::cout << stof(temp) << std::endl;
}
}
}
// file is closed when infile goes out of scope
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment