Created
January 12, 2018 10:08
-
-
Save JeroenDM/669caa9da6bc33356aa3ffec23a32564 to your computer and use it in GitHub Desktop.
I always forget how to read files with numbers in c++.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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