数据的输入输出采取字符流的形式,字符入、字符出(character in character out)。

An ostream converts typed objects to a stream of characters (bytes):

c语言字符型数据的输入输出(C输入输出的字符转换)(1)

An istream converts a stream of characters (bytes) to typed objects:

c语言字符型数据的输入输出(C输入输出的字符转换)(2)

数据输入时,会首先在Buffer中寻找是否有数据,有数据则读取,没有数据则等待输出。

整数、浮点型、字符串的输入稍有不同,整数、浮点型的输入在缓冲区读取数据时,如果遇到whitespace字符,会忽略掉,仍然等待输入。而输入字符串则不同,如果缓冲区中存在whitespace数据,如'\n',则会直接读取并赋值给字符串变量,所以通常的做法是要将这样的空白字符处理掉,如使用一次或循环使用getchar()函数,但不推荐使用fflush(stdin);,因为fflush()默认为stdout,对于stdin是未定义行为。

Streams have a so-called current position, The current position is the position in the stream where the next read or write operation will take place.

流有一个所谓的当前位置,当前位置是流中下一个读或写操作将发生的位置。

对于需要多次输入的数据可以一次性输入完,各语句根据当前读的位置逐输入从Buffer中读取数据。

cout << "abc"; cout.flush(); // abc is written to the console. cout << "def"; cout << endl; // def is written to the console.

NOTE: Not all output streams are buffered. The cerr stream, for example, does not buffer its output.

注意:并非所有的输出流都是缓冲的。例如,cerr流不缓冲其输出。

Remember that the >> operator tokenizes values according to white space, so the getReservation_Data() function does not allow you to enter a name with white space. A solution is using unget(). Note also that even though the use of cout does not explicitly flush the buffer using endl or flush(), the text will still be written to the console because the use of cin immediately flushes the cout buffer; they are linked together in this way.

请记住>>运算符根据空白标记值,因此getReservation_Data()函数不允许您输入带有空格的名称。一种解决的方案是使用unget()函数。还要注意的是,即使cout的使用没有使用endl或flush()显式刷新缓冲区,文本仍将写入控制台,因为使用cin会立即刷新cout缓冲区;它们以这种方式连接在一起。

For most purposes, the correct way to think of an input stream is as a one-way chute. Data falls down the chute and into variables. The unget() method breaks this model in a way by allowing you to push data back up the chute.

在大多数情况下,将输入流视为单向斜槽是正确的。数据从斜槽中滑落到变量中。unget()方法在某种程度上打破了这个模型,允许您将数据推回到滑槽上。

A call to unget() causes the stream to back up by one position, essentially putting the previous character read back on the stream. You can use the fail() method to see if unget() was successful or not. For example, unget() can fail if the current position is at the beginning of the stream.

对unget()的调用会导致流回退一个位置,实质上是将之前读取的字符放回流中。可以使用fail()方法查看unget()是否成功。例如,如果当前位置位于流的开头,unget()可能会失败。

The putback() method, like unget(), lets you move backward by one character in an input stream. The difference is that the putback() method takes the character being placed back on the stream as a parameter:

putback()方法与unget()类似,允许在输入流中向后移动一个字符。不同之处在于putback()方法将放回流中的字符作为参数:

char ch1; cin >> ch1; cin.putback('e'); // 'e' will be the next character read off the stream.

磁盘文件的输入输出也存在同样的缓冲机制:

c语言字符型数据的输入输出(C输入输出的字符转换)(3)

-End-

,