Reputation: 58087
I'm trying to read an ifstream
into a string, where I can set the number of characters being read. I've read the documentation for ifstream.get()
and ifstream.getline()
, but neither of those accomplish what I want.
Given the following string:
asdfghjklqwertyuiop
I want to read in varying number of characters at a time into a string. I've started like this, but I'm getting an error that there's no function that will take a string as the first parameter:
string destination;
int numberOfLettersToGet = 1;
while (inputstream.get(destination, numberOfLettersToGet)){
//Do something.
}
What can I use instead of inputstream.get()
?
Upvotes: 0
Views: 1027
Reputation: 136256
You may like to use read
and gcount
member-functions of std::istream
. get
appends a zero-terminator, which is unnecessary when you read into std::string
.
std::string destination;
int numberOfLettersToGet = 1;
destination.resize(numberOfLettersToGet);
std::streamsize n = inputstream.gcount();
inputstream.read(&destination[0], numberOfLettersToGet);
destination.resize(inputstream.gcount() - n); // handle partial read
Upvotes: 1
Reputation: 1054
istream::get
returns the character as an integer, so you simply need to append the returned character as the next character of the string. e.g.
while (string.push_back(inputstream.get()))
{ //...
}
Upvotes: 1