如何在 C++ 中设置流的最大读取长度?

发布于 2024-08-25 15:12:25 字数 208 浏览 8 评论 0原文

我正在将数据从流读取到给定长度的字符数组中,并且我想让读取的最大宽度足够大以适合该字符数组。

我使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

時窥 2024-09-01 15:12:25

如果您正在处理文本,则需要查找 get 函数:http: //cppreference.com/wiki/io/get

const int size = 200;
char myArray[size] = {};

cin.get(myArray, size);

注意:仅读取 size - 1 个字符,这会在 myArray 中留下 NULL 终止符。

如果它是原始数据,您可能更喜欢readhttp://cppreference。 com/wiki/io/read

const int size = 200;
char myArray[size] = {};

cin.read(myArray, size);

size 字节被读取。

If you're processing text, you're looking for the get function: http://cppreference.com/wiki/io/get

const int size = 200;
char myArray[size] = {};

cin.get(myArray, size);

Note: 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/read

const int size = 200;
char myArray[size] = {};

cin.read(myArray, size);

size bytes are read.

冰之心 2024-09-01 15:12:25
char x[4];
cin.width(4);
cin >> x;
cout << x;

输入:“abcdef”

输出:“abc”
x[3] 是 null 终止字符)

宽度在这种情况下效果很好。

注意:经验测试表明 cin.width 调用仅持续一次流操作。使用cin>>可能会更方便。 setw(4) >>> x; 相反,尽管这需要 iomanip

char x[4];
cin.width(4);
cin >> x;
cout << x;

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 requires iomanip.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文