如何在 C++ 中设置流的最大读取长度?
我正在将数据从流读取到给定长度的字符数组中,并且我想让读取的最大宽度足够大以适合该字符数组。
我使用 char 数组的原因是我的规范的一部分是任何单个标记的长度不能超过某个值,因此我为自己节省了一些构造函数调用。
我认为 width() 做了我想要的,但我显然错了......
编辑:我使用流提取运算符来执行提取,因为这些是平面文本文件,其值由空格分隔。
I'm reading data from a stream into a char array of a given length, and I'd like to make the maximum width of read to be large enough to fit in that char array.
The reason I use a char array is that part of my specification is that the length of any individual token cannot exceed a certain value, so I'm saving myself some constructor calls.
I thought width() did what I wanted, but I was apparently wrong...
EDIT: I'm using the stream extraction operators to perform the extraction, since these are flat text files with values separated by whitespace.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您正在处理文本,则需要查找
get
函数:http: //cppreference.com/wiki/io/get注意:仅读取
size - 1
个字符,这会在 myArray 中留下 NULL 终止符。如果它是原始数据,您可能更喜欢
read
:http://cppreference。 com/wiki/io/readsize
字节被读取。If you're processing text, you're looking for the
get
function: http://cppreference.com/wiki/io/getNote: only
size - 1
characters are read, which leaves a NULL terminator in myArray.If it's raw data, you'd probably prefer
read
: http://cppreference.com/wiki/io/readsize
bytes are read.输入:“abcdef”
输出:“abc”
(
x[3]
是 null 终止字符)宽度在这种情况下效果很好。
注意:经验测试表明 cin.width 调用仅持续一次流操作。使用
cin>>可能会更方便。 setw(4) >>> x;
相反,尽管这需要iomanip
。Input: "abcdef"
Output: "abc"
(
x[3]
is null terminating char)Width works fine in this case.
Note: Empirical testing indicates that the cin.width call only lasts for one stream operation. It may be more convenient to use
cin >> setw(4) >> x;
instead, though this requiresiomanip
.