I have a situation where I loop through the first 64 lines of a file and save each line into a string. The rest of the file is unknown. It may be a single line or many. I know that there will be 64 lines at the beginning of the file but I do not know their size.
How can I save the entirety of the rest of the file to a string?
This is what I currently have:
std::ifstream signatureFile(fileName);
for (int i = 0; i < 64; ++i) {
std::string tempString;
//read the line
signatureFile >> tempString;
//do other processing of string
}
std::string restOfFile;
//save the rest of the file into restOfFile
Thanks to the responses this is how I got it working:
std::ifstream signatureFile(fileName);
for (int i = 0; i < 64; ++i) {
std::string tempString;
//read the line
//using getline prevents extra line break when reading the rest of file
std::getline(signatureFile, tempString);
//do other processing of string
}
//save the rest of the file into restOfFile
std::string restOfFile{ std::istreambuf_iterator<char>{signatureFile},
std::istreambuf_iterator<char>{} };
signatureFile.close();
One of std::string
's constructors is a template that takes two iterators as parameters, a beginning and an ending iterator, and constructs a string from the sequence defined by the iterators.
It just so happens that std::istreambuf_iterator provides a suitable input iterator for iterating over the contents of an input stream:
std::string restOfFile{std::istreambuf_iterator<char>{signatureFile},
std::istreambuf_iterator<char>{}};