我创建的c++istream对象和cin之间的区别在哪里,它在库中的可见位置在哪里

Where is the difference between c++ istream objects I create and cin and where is it visible in the library

本文关键字:在哪里 位置 区别 c++istream 创建 对象 之间 cin      更新时间:2023-10-16

cin是一个istream对象。

它是在iostream:中创建的

/**
*  @name Standard Stream Objects
*
*  The &lt;iostream&gt; header declares the eight <em>standard stream
*  objects</em>.  For other declarations, see
*  http://gcc.gnu.org/onlinedocs/libstdc++/manual/io.html
*  and the @link iosfwd I/O forward declarations @endlink
*
*  They are required by default to cooperate with the global C
*  library's @c FILE streams, and to be available during program
*  startup and termination. For more information, see the section of the
*  manual linked to above.
*/
//@{
extern istream cin;       /// Linked to standard input
extern ostream cout;      /// Linked to standard output
extern ostream cerr;      /// Linked to standard error (unbuffered)
extern ostream clog;      /// Linked to standard error (buffered)
#ifdef _GLIBCXX_USE_WCHAR_T
extern wistream wcin;     /// Linked to standard input
extern wostream wcout;    /// Linked to standard output
extern wostream wcerr;    /// Linked to standard error (unbuffered)
extern wostream wclog;    /// Linked to standard error (buffered)
#endif
//@}

我试着创建另一个istream,并像cin一样使用它——它不起作用。

#include<iostream>
int main()
{
std::istream dada;
int foo;
dada>>foo;
std::cout<<foo; 
return 0;
}

因为它不会编译。我只是浏览库文件,了解cin是如何链接到我的shell的,但另一个istream对象不是。有人能解释一下吗?我对cinget链接到STDIN缓冲区的文件感兴趣。

非常感谢。

std::istream只是一个门面:它提供了有用的函数和运算符,允许您提取数字、任意数量的字符和其他东西,而无需篡改底层流,而底层流实际上只是一个字符序列。

实际工作由streambuf对象完成。流存储指向它的指针,并在需要时从中请求字符。所以,当您从流中读取数字时,流会向缓冲区请求字符,直到它找到非数字,然后将数字字符转换为数字。

现在回答你的问题。标准确实要求std::cin的类型为std::istream,但它没有说明它的缓冲区是什么类型(除此之外,它是从std::streambuf派生的)。Standard也没有提供这样的缓冲区供用户使用,因此它可以被视为编译器魔术

实现这种缓冲区的唯一标准方法是创建自己的缓冲区类,从streambuf派生,它将与STDIN(或cin,但这很奇怪)交互,并将指向它的指针传递给istream构造函数。

或者,您可以使用std::cin自己的缓冲区:

std::istream my_cin(std::cin.rdbuf());
int x;
my_cin >> x;

cin是使用STDIN缓冲区的istream对象的实现。

如果您创建了其他对象,但没有缓冲区映射,它将不起作用。

这就像您尝试使用ifstream从文件中读取,但不使用相同的文件名。

它类似于使用fscanf(stdin,"%s",p),stdin是固定的文件句柄,但它实际上是stdin缓冲区的一些包装器。