C++:从包含空字符的文件中读取
不幸的是,我必须从文件中读取数据以进行分配,而不是用空格分隔各个字段,而是使用空字符。当从文件中获取整数时,它们被很好地提取,但是对于字符串,我只是从未初始化的字符数组中得到空格和垃圾。关于如何将字符提取到我的字符数组中而忽略空字符的任何想法。
编辑:
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;
是我现在使用的代码,不幸的是 fName 没有再次获取除 null 之外的任何内容 lName 正在获取 fName 的字符串值。正在考虑将数字作为字符串获取并进行转换。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
getline
并传递\0
(空字符)作为分隔符。Use
getline
and pass\0
(null character) as the delimiter.std::getline
有一个可选参数,它是分隔符(默认情况下'\n'
)。std::getline
has an optional argument which is the delimiter character ('\n'
, by default).http://www.cplusplus.com/reference/iostream/istream/read/ 一次性读取文件到缓冲区,然后从那里继续。
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,