任何方式来摆脱空字符在结尾的istream得到? [英] Any way to get rid of the null character at the end of an istream get?
问题描述
我目前正试图写一点代码来读取一个文件,并提取它的位并将其保存为变量。
这里是相关的代码: / p>
字节地址[10];
ifstream tracefile;
tracefile.open(trace.txt);
tracefile.seekg(2,ios :: beg);
tracefile.get(address,10,'');
cout<地址;
文件内容:(只是第一行)
R 0x00000000
m有地址错过最后的'0',因为它在那里放一个/ 0字符,我不知道如何解决这个问题?所以它输出:
0x0000000
$ b b
我也有问题
tracefile.seekg(2,ios :: cur) ;
它似乎不工作,因此为什么我把它改为ios :: beg尝试和得到一些工作,虽然显然,一旦我尝试阅读多行之后,将无法使用。
任何帮助将不胜感激。 >
ifstream :: get()
将尝试生成一个以null结尾的C字符串,但是没有为其提供足够的空间。
您可以:
- 分配
;
(或更大)以容纳长度超过9个字符的以null结尾的字符串。 - 使用
ifstream :: read()
- Allocate
char address[11];
(or bigger) to hold a null-terminated string longer than 9 characters. - Use
ifstream::read()
instead to read the 10 bytes without a null-terminator.
如果您想要一个可以动态计算行长度的缓冲区,请使用 std :: getline
与 std :: string
。
std :: string buffer;
tracefile.seekg(2,ios :: beg);
std :: getline(tracefile,buffer);
编辑2
如果只想读取下一个空格,请使用:
std :: string buffer;
tracefile.seekg(2,ios :: beg);
tracefile>>缓冲;
I'm currently trying to write a bit of code to read a file and extract bits of it and save them as variables.
Here's the relevant code:
char address[10]; ifstream tracefile; tracefile.open ("trace.txt"); tracefile.seekg(2, ios::beg); tracefile.get(address, 10, ' '); cout << address;
The contents of the file: (just the first line)
R 0x00000000
The issue I'm having is that address misses the final '0' because it puts a /0 character there, and I'm not sure how to get around that? So it outputs:
0x0000000
I'm also having issues with
tracefile.seekg(2, ios::cur);
It doesn't seem to work, hence why I've changed it to ios::beg just to try and get something work, although obviously that won't be useable once I try to read multiple lines after one another.
Any help would be appreciated.
解决方案
ifstream::get()
will attempt to produce a null-terminated C string, which you haven't provided enough space for.You can either:
Edit:
If you want a buffer that can dynamically account for the length of the line, use
std::getline
with astd::string
.std::string buffer; tracefile.seekg(2, ios::beg); std::getline( tracefile, buffer );
Edit 2
If you only want to read to the next whitespace, use:
std::string buffer; tracefile.seekg(2, ios::beg); tracefile >> buffer;
这篇关于任何方式来摆脱空字符在结尾的istream得到?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!