如何读取存储在输入流缓冲区中的字符数

How to read number of characters stored in input stream buffer

我有一个简单的问题 - 我如何才能在控制台 window 中将某些内容写入 std::cin 而不将其分配给 stringchar[]?然后如何读取缓冲区中存储的字符数?

假设我想创建一个 char 的数组,但它的大小应为输入长度。我可能会创建一个缓冲区或一个大尺寸的变量来存储输入,然后读取它的长度,为我的 char 数组分配内存并复制它。但我们还要说我是一个纯粹主义者,我不想使用任何额外的(流缓冲区除外)内存。是否有可能访问 std::cin 缓冲区,读取存储的字符数并将它们复制到我的数组中?我花了几个小时试图找到答案,阅读了 cpp 参考资料,但我真的找不到解决方案。我什至找不到是否有可能在不将其分配给变量的情况下将某些内容写入 std::cin 缓冲区,也就是执行 cin >> variable。如果您对此问题有其他解决方案,我将不胜感激。

此外,有人知道我在哪里可以找到有关缓冲区工作原理的信息(指计算机存储键盘输入的位置、输入的处理方式以及 iostream 如何与计算机一起从中提取数据)。

非常感谢!

首先,为了填充输入缓冲区,您需要执行某种读取操作。读取操作可能不需要将读取的内容放入变量中。例如,cin.peek() may block until the user enters some value and returns the next character that will be read from the buffer without extracting it or you could also use cin.getcin.putback.

然后您可以使用 streambuf::in_avail 函数来确定输入缓冲区中有多少个字符,包括换行符。

考虑到这一点,您可以这样做:

char ch;
cin.get(ch);//this will block until some data is entered
cin.putback(ch);//put back the character read in the previous operation
streamsize size=cin.rdbuf()->in_avail();//get the number of character in the buffer available for reading(including spaces and new line)
if(size>0)
{
    char* arr=new char[size];//allocate the size of the array(you might want to add one more space for null terminator character)

   for(streamsize i=0;i<size;i++)
        cin.get(arr[i]);//copy each character, including spaces and newline, from the input buffer to the array

   for(streamsize i=0;i<size;i++)
        cout<<arr[i];//display the result
}

话虽这么说,我相信您这样做有特定的原因,但我认为这样做 I/O 不是一个好主意。如果您不想估计输入所需的字符数组的大小,那么您始终可以使用 std::string 并改为读取输入。