C++: reading from a file with null characters
I have to read data from a file for an assignment unfortunately instead of spaces separating the various fields there are null characters. When taking integers from the file they are extracted fine however with th开发者_JAVA技巧e strings i just get a blanks space and garbage from my uninitialized character array. Any ideas as how to just extract the characters into my character array ignoring the null characters.
EDIT:
char fName[15],lName[15],pMethod[5],roomType[10],purpose[15];
int days, roomNum;
long guestID;
datafile>>guestID;
datafile.getline(fName,15,'\0');
datafile.getline(lName,15,'\0');
cout<<guestID<<endl;
cout<<fName<<endl;
cout<<lName<<endl;
is the code I'm using now unfortunately fName isnt grabbing anything other than null again and lName is getting fName's string value. Was thinking about just getting the numbers as string and converting them.
Use getline
and pass \0
(null character) as the delimiter.
std::getline
has an optional argument which is the delimiter character ('\n'
, by default).
http://www.cplusplus.com/reference/iostream/istream/read/ read the file to buffer in one go and then proceed from there.
Loop throught the bytes and ignore the null character bytes,
精彩评论