问题
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 the 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.
回答1:
Use getline and pass \0
(null character) as the delimiter.
回答2:
std::getline
has an optional argument which is the delimiter character ('\n'
, by default).
回答3:
http://www.cplusplus.com/reference/iostream/istream/read/ read the file to buffer in one go and then proceed from there.
回答4:
Loop throught the bytes and ignore the null character bytes,
来源:https://stackoverflow.com/questions/4071313/c-reading-from-a-file-with-null-characters