   Reading from a std::ifstream to a std::string
  Hi.Is there anyone who can tell me how to read a specified number of characters from a std::ifstream to a std::string?I''ll give you an example:#include <iostream>#include <fstream>using namespace std;int main (){string str;ifstream stream;stream.open("c:/test.txt",ios::in | ios::binary);   //here I want to read for instance the 10 first characters in text.txt into the std::string str   //I have tried stream.read((char*)&str,10); , but that didn''t go very well stream.close();cout << str.c_str();return 0;}I hope anyone can help me.Thanks in advance"The mistakes are all waiting to be made. 
  What does your documentation say?Mine says basic_istream::read and basic_istream::get take arrays. So you need to pass an array.You'll need to use the array and then copy it into a string. #include <iostream>#include <fstream>int main () {    const int arraySize = 10;    char array[arraySize];    std::ifstream stream;    stream.open("c:/test.txt",std::ios::in | std::ios::binary);    stream.read(array, arraySize);    stream.close();    std::string str(array);    std::cout << str.c_str();    return 0;} [edited by - petewood on February 6, 2004 12:56:34 PM];  You should be able to do:ifstream fin ("text.txt";string s;fin.width(10);fin >> s;  At which point s will contain 10 or less characters.Here''s the deal on operator>> for strings:quote:Reads s from the input stream is. Specifically, it skips whitespace, and then replaces the contents of s with characters read from the input stream. It continues reading characters until it encounters a whitespace character (in which case that character is not extracted), or until end-of-file, or, if is.width() is nonzero, until it has read is.width() characters. This member function resets is.width() to zero.To say it''s not quite what you want is fair.  You should probably use a character array if you actually want 10 characters.  If you want the whole line, just use getline (fin, s); ;  I also just thought of this: it''d be really easy to use getline() and work with the string in substrings of 10 characters.while (getline (fin,sin)){   string s = sin.substr(0, 10);   // Do whatever now with s, get new strings as you need to   // from sin.} ;  I came up with this:It uses an strstream object. // suppose you want to read n characters into a stringstrstream ss;ss << infile.rdbuf(); string str( ss.str(), n );;  Thanks for the replies.I''ll surely get it to work now The reason I asked in the first place is that I need to load strings from a binary file, that is a specified length, that is stored right before the strings in the file. Thanks a lot for the help  "The mistakes are all waiting to be made. ;  btw, instead of using arrays you could use an std::vector sized to the right size and then supply the function with &vec[0] instead of the array (used this method when talking to winsock, works perfectly) 