How to set maximum read length for a stream in C++?

房东的猫 提交于 2019-12-03 16:58:22
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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!