- 浏览: 1291376 次
-
文章分类
最新评论
-
char1st:
2b 青年 mongodb
我们该如何设计数据库(一) -
什么向往:
二逼青年的做法的确让人有点觉得:靠,这都行!!
我们该如何设计数据库(一) -
cloudmail:
如果只用到name来查询的话,支持2b做法总之,2b做法是最容 ...
我们该如何设计数据库(一)
C++ Stream I/O
C++ Stream I/O
- Stream Input/Output
- Stream I/O Applications
- Stream Output Concept
- Stream Input Concept
- Using C++ Objects
- Standard Output Stream
- Standard Output Stream, Cont.
- Formatted Output
- Standard Input Stream
- Standard Input Stream, Cont.
- Formatted Input
- Unformatted I/O Example
- What is EOF?
- Unformatted I/O Summary
- Formatted I/O
- Floating-point Precision
- Floating-point Manipulators
- Floating-point Example
- C++ String
- Line-based Input, std::getline
- String Stream
- Low-level I/O using String Stream
- Field Width
- Fill Character
- Field Alignment
- Alignment of Numeric Fields
- Scientific Notation
- Normalized Scientific Notation
- More Manipulator Examples
- Manipulators for Integer Data Types
- cin interpretation of 0 and 0x prefixes
- Manipulators for Floating-point Data Types
- C++ Standard Library Objects
- Stream Functionality
1. Stream Input/Output
Standard Outputcout,cerr
Standard Inputcin
Formatting
Error handling
-
File I/O (later)
2. Stream I/O Applications
network communication
encryption
data compression
persistent storage of objects
-
character-oriented input and output
3. Stream Output Concept
|
Output stream buffer:
H | E | L | L | O | \n | 1 | 2 | 3 | ... | ... |
4. Stream Input Concept
Input stream buffer:
4 | 5 | 6 | \n | 7 | 8 | 9 | \n | ... | ... |
|
5. Using C++ Objects
-
Objects are C++variablesofuser-defined types. They are declared as
typename object_name;
-
For example, ifShape3Dis a user-defined type, then we could try
Shape3D widget; // create object named "widget" widget.display( parameters ); // call member function with parameters widget.reset( ); // call member function without parameters
Dot-notation is used to access functions built into objects.
-
Alternatively, some objects may allow use of arithmetic operators. For example,
std::cout << widget; // display widget on console output device
6. Standard Output Stream
typename object name ------------ ----------- std::ostream std::cout; // cout is a predefined object
-
Usage example:
#include <iostream> // C++ standard library header using std::cout; // cout declared inside std namespace int main() { int x = 65; cout << x; // display value of number 65 cout.put( x ); // display character 'A' return 0; } /* This program prints: 65A */
7. Standard Output Stream, Cont.
std::coutis a pre-defined object
-
We need to
#include <iostream>
to bringstd::coutinto our program
std::coutis attached to thestandard output device, which can be console display, file, or printer.
-
I/O redirection to file or printer is made easy:
CMD> myprogram > myfile.txt
The above command sends standard output tomyfile.txt
8. Formatted Output
|
|
9. Standard Input Stream
typename object name ------------ ----------- std::istream std::cin; // cin is a predefined object
-
Usage:
// formatted input of C++ variables int x; cin >> x; // unformatted input of single characters char x = cin.get( ); // line-based input of text strings string text; getline( cin, text );
10. Standard Input Stream, Cont.
std::cinis a pre-defined object
-
We need to have
#include <iostream>
to bringstd::cininto our program
std::cinis attached to astandard input device
-
Example of I/O redirection from file or another device:
CMD> myprogram < myfile.txt
The above command gets standard input frommyfile.txt
11. Formatted Input
-
Formatted inputmeans
reading expected type and format
automatic whitespace processing
#include <iostream> int main( ) { int one; int two; std::cout << "Please enter two integers: "; std::cin >> one >> two; return 0; }
12. Unformatted I/O Example
-
Unformatted inputmeans
reading individual characters
discovering data type and format as you read
#include <iostream> int main() { int onechar; // using int because char cannot represent EOF while ( ( onechar = std::cin.get() ) != EOF ) { std::cout.put( onechar ); } return 0; }
13. What is EOF?
AcronymEOFstands for condition known asend of file.
When reading from a file, the condition occurs naturally at the end of file.
-
To keep things consistent, the condition is also triggered when user enters
CTRL+Z (on Windows machine) CTRL+D (on Unix machine)
on the keyboard.
-
EOFis asymbolthat becomes defined after
#include <iostream>
14. Unformatted I/O Summary
|
|
15. Formatted I/O
-
Floating-point values by default use fixed-point notation:
#include <iostream> int main() { const double PI = 3.1415926; std::cout << PI << '\n'; return 0; } /* Output: 3.14159 */
16. Floating-point Precision
|
|
17. Floating-point Manipulators
-
There are three possible ways to format floating point values:
cout << value // default cout << fixed << value cout << scientific << value
-
Infixedandscientificnotations precision specifies exactlyhow many digits to displayafter the decimal point, even if they are trailing decimal zeros.
18. Floating-point Example
-
#include <iostream> using namespace std; int main() { const double PI = 3.1415926; cout.precision( 7 ); cout << fixed << "fixed format: " << PI << '\n'; cout << scientific << "scientific format: " << PI << '\n'; // back to default format: cout.unsetf( ios_base::fixed ); cout.unsetf( ios_base::scientific ); cout << "default format: " << PI << '\n'; return 0; } /* Output: fixed format: 3.1415926 scientific format: 3.1415926e+000 default format: 3.141593 */
19. C++ String
|
|
20. Line-based Input, std::getline
-
#include <iostream> #include <string> using namespace std; int main() { string text_line; // Line-based input of text: cout << "Type something: "; getline( cin, text_line ); cout << "You typed: "; cout << text_line; cout << '\n'; return 0; }
21. String Stream
-
#include <cassert> #include <string> #include <sstream> int main() { const double PI = 3.1415926; double value; std::stringstream buffer; // text buffer buffer.precision( 8 ); // increase default precision (*) buffer << PI; // formatted output buffer >> value; // formatted input assert( PI == value ); std::string text; text = buffer.str( ); // returns std::string buffer.str( "" ); // clear buffer return 0; }
(*) try commenting out precision change and see what happens
22. Low-level I/O using String Stream
-
#include <cassert> #include <iostream> #include <sstream> using namespace std; int main() { stringstream buffer; int onechar; // because char cannot represent EOF cout << "Enter some text: "; while ( ( onechar = cin.get() ) != EOF ) { if ( onechar == '\n' ) { break; // exit loop at the end of the line } else if ( isalpha( onechar ) ) { buffer << "alpha: " << char( onechar ) << '\t' << onechar <<'\n'; } else if ( isdigit( onechar ) ) { buffer << "digit: " << char( onechar ) << '\t' << onechar <<'\n'; } else { buffer << "other: " << char( onechar ) << '\t' << onechar <<'\n'; } } cout << buffer.str() << '\n'; // str() returns string return 0; }
23. Field Width
Manipulatorstd::setw( n )determines minimum output widthn.
-
Requires header
#include <iomanip>
-
If output is shorter than thefield widthn, the output is padded withfill characters.
#include <iostream> #include <iomanip> using namespace std; int main () { cout << setw( 40 ) << "Hello"; return 0; } /* Output: Hello */
24. Fill Character
-
Fill charactercan be changed bysetfillmanipulator:
#include <iostream> #include <iomanip> using namespace std; int main () { cout << setfill( '?' ) << setw( 40 ) << "Hello"; return 0; } /* Output: ???????????????????????????????????Hello */
25. Field Alignment
leftappends fill characters at the end.
-
rightinserts fill characters at the beginning.
#include <iostream> #include <iomanip> using namespace std; int main () { cout << left << setfill( '?' ) << setw( 40 ) << "Hello"; return 0; } /* Output: Hello??????????????????????????????????? */
26. Alignment of Numeric Fields
-
Adjusting numeric fields:
#include <iostream> #include <iomanip> using namespace std; int main() { int x = -1234; cout << setw( 10 ) << internal << x << '\n'; cout << setw( 10 ) << left << x << '\n'; cout << setw( 10 ) << right << x << '\n'; return 0; } /* Output: - 1234 -1234 -1234 */
27. Scientific Notation
Scientific notation(exponential notation) adjusts specifieddecimal pointto the left or to the right according to the specified value of exponente.
-
Thee-suffix representstimes ten raised to the power. For example,
1e-2 == 0.01 == 1×10-2 1e-1 == 0.10 == 1×10-1 1e-0 == 1.00 == 1×100 1e+0 == 1.00 == 1×100 1e+1 == 10.00 == 1×101 1e+2 == 100.00 == 1×102
28. Normalized Scientific Notation
-
Normalized scientific notationexpects absolute partA(*)of the numberA×10bto be in the range
1 <=A< 10
-
Try the following program to convert numbers from scientific notation to ordinary decimal notation:
#include <iostream> #include <iomanip> using namespace std; int main() { for (;;) { double dbl; cin >> dbl; cout << setw( 14 ) << showpoint << dbl << '\n'; } return 0; }
-
________________
(*) the absolute partAis also known asmantissa.
29. More Manipulator Examples
-
#include <iostream> #include <iomanip> using namespace std; int main() { /* 5600 */ cout << setw( 14 ) << 56e2 << '\n'; /* 5600.00 */ cout << setw( 14 ) << showpoint << 56e+2 << '\n'; /*2.345678e+002 */ cout << setw( 14 ) << scientific << 234.5678 << '\n'; /* 255 */ cout << setw( 14 ) << 255 << '\n'; /* ff */ cout << setw( 14 ) << hex << 255 << '\n'; /* 377 */ cout << setw( 14 ) << oct << 255 << '\n'; /* 1 */ cout << setw( 14 ) << true << '\n'; /* true */ cout << setw( 14 ) << boolalpha << true << '\n'; /* 1234.567890 */ cout << setw( 14 ) << fixed << 1234.56789 << '\n'; /* 1234.568 */ cout << setw( 14 ) << fixed << setprecision(3) << 1234.56789 << '\n'; return 0; } /* Output: 5600 5600.00 2.345678e+002 255 ff 377 1 true 1234.567890 1234.568 */
30. Manipulators for Integer Data Types
-
The following areinteger output manipulators:
boolalpha: use symbolic representation oftrueandfalsewhen inserting or extractingboolvalues. By default,boolvalues inserted and extracted as numeric values1and0.
dec: insert or extract integer values in decimal (base 10) format.
hex: insert or extract integer values in hexadecimal (base 16) format, such as "0xFF" or simply "FF".
oct: insert or extract integer values in octal format, e.g. "077"
showbase: insert a prefix that reveals the base of an integer value.
noshowbase: reverse back to baseless integer output format.
Note: the above manipulators aresticky: they persist until another manipulator is applied.
-
The data type manipulators can be applied to bothinputandoutputstreams.
31. cin interpretation of 0 and 0x prefixes
cin.unsetf( ios::dec ); // Interpret 0 and 0x as hexadecimal and octal prefixes cin.unsetf( ios::oct ); // Ignore octal prefix, interpret 077 as decimal 77 cin.unsetf( ios::dec ); cin.setf( ios::oct ); // All integers now expected to be octal base cin.unsetf( ios::dec ); cin.setf( ios::hex ); // All integers now expected to be base-16:
Sample programcin_setf.cpp(download) illustrates integer base/prefix manipulation and rudimentary format-related error recovery.
-
See also<noindex><a href="http://www.cplusplus.com/reference/iostream/ios_base/setf.html" target="_blank"><tt>cin.setf()</tt></a></noindex>and<noindex><a href="http://www.cplusplus.com/reference/iostream/ios_base/unsetf.html" target="_blank"><tt>cin.unsetf()</tt></a></noindex>documentation.
32. Manipulators for Floating-point Data Types
showpoint: insert a decimal point unconditionally in a generated floating-point field.
-
fixed: insert floating-point values in fixed-point format. For example,
default format for1234.56789is1234.57,
fixed makes it1234.56789.
-
scientific: insert floating-point values in scientific format with an exponent field. For example,
default format for1234.56789is1234.567,
scientificmakes it1.234568e+03.
-
Note: the above manipulators aresticky: they persist until another manipulator is applied.
33. C++ Standard Library Objects
-
typename object name ------------ ----------- std::ostream std::cout; // predefined object std::istream std::cin; // predefined object std::string text; // text data std::stringstream buffer; // text buffer
相关推荐
C++中的I/O流是程序处理输入和键盘输入、输出和屏幕输出的一种统一方式。这一概念在第二章“作为对象和类介绍的I/O流”中被深入探讨。本章涵盖了几个关键知识点,包括基本的文件I/O、流工具、字符I/O以及继承。 2.1...
在 C++ 中,I/O 流主要通过流类(stream)来实现,包括输入流(input stream)和输出流(output stream)。在这个过程中,控制符(Manipulator)和特殊字符(Escape Sequence)扮演着非常重要的角色。 控制符是指...
在本文中,我们将深入探讨如何使用C++编程语言来实现基于WSAEventSelect的I/O模型。WSAEventSelect是Windows Socket API(Winsock)提供的一种异步I/O机制,它允许应用程序通过等待网络事件来处理多个套接字。这个...
本文实例讲述了C++中I/O模型的select模型用法。分享给大家供大家参考。具体实现方法如下: 代码如下:void main() { CInitSock initSock; USHORT nPort = 9999; //监听的端口 SOCKET sListen = ::...
C++Stream风格的异步日志,如"Muduo"日志,是一种高效且实用的日志解决方案。Muduo是由知名C++开发者陈硕创建的一个轻量级网络库,其异步日志组件设计巧妙,不仅提供了高性能的日志记录,而且去除了对Boost库的依赖...
在实际项目中,可能还需要考虑错误处理、多线程或异步I/O等复杂情况,以确保系统的稳定性和性能。而15json这个文件可能是包含相关代码示例或测试数据的压缩包,对于学习和实践上述知识非常有帮助。
C++编程语言中的I/O流是程序设计中的一个重要概念,特别是在处理输入输出操作时。本章节将深入探讨第二章——I/O流,作为面向对象和类的初步介绍。以下是关于I/O流及其基本文件I/O的详细说明: 2.1 流与基本文件I/O...
描述中的"help library for vC++ landscape io"进一步确认这是一份关于Visual C++的I/O(输入/输出)操作的指导文档库,特别关注的是在图形化界面或命令行界面下的I/O处理。 在开发C++应用程序时,Visual Studio是...
C++中的I/O操作建立在流(Stream)的概念之上,流可以被看作是字节序列,通过流,程序能够以类型感知的方式处理各种数据。C++提供了两种级别的I/O功能:低级I/O主要关注字节级别的数据传输,而高级I/O则允许将字节...
2. **类型安全**:C++的I/O操作是类型安全的,确保在输入/输出过程中数据类型不会发生不应有的转换。 3. **易扩展**:C++通过运算符重载使得流操作符`和`>>`能方便地用于插入(输出)和提取(输入)操作,这使得扩展...
C++的I/O流库是其强大的特性之一,它为程序的数据输入和输出提供了高效、灵活的方法。在C++中,输入输出操作是通过“流”(stream)进行的,数据可以流经不同的设备,如键盘、屏幕、磁盘文件等。本章主要围绕C++的I/...
在Windows系统中,I/O Completion Ports (IOCP) 是一种高效能的多线程I/O模型,用于处理大量并发的I/O操作。本示例主要介绍如何使用C++实现基于IOCP的网络通信,这对于理解和优化高并发服务器的性能至关重要。 IOCP...
C++中的I/O操作基于流(stream)的概念,流是一个字节序列。有两个派生自共同基类的基本流类:`basic_istream`,用于输入流,以及`basic_ostream`,用于输出流。这些类位于标准的I/O层次结构中,如`ios_base`和`base...
在C++的世界里,输入输出流(I/O Stream)是一项核心且强大的技术,它不仅简化了I/O操作,还提供了更为安全和高效的方式。本章节深入探讨C++输入输出流的基础概念、设计理念以及其相较于传统C语言I/O库的优势。 ###...
在C++编程中,输入/输出(I/O)机制是一个重要的组成部分,但它们不是语言的基本特性,而是通过类库来提供的。本章主要探讨的是C++的I/O类层次结构,包括不同类型的输入/输出流类、操纵符、文件流以及字符流。 12.1...
本章主要探讨的是C++中的输入输出机制,特别是涉及到了流(Stream)、输入输出缓冲以及基于不同媒介的I/O操作。 首先,C++将输入输出视为一种数据流,这意味着数据以序列的形式流动,可以从外围设备流向内存(输入...
serverSocket = socket(AF_INET, SOCK_STREAM, 0); SOCKADDR_IN addr; addr.sin_family = AF_INET; addr.sin_port = htons(6000); addr.sin_addr.S_un.S_addr = inet_addr(CS); bind(serverSocket, (SOCKADDR*...
本文将重点讨论C++中关于I/O库的基础知识和类库,特别是涉及的格式化输入/输出以及文件I/O。 首先,C++中的I/O库在老版本中使用`<iostream.h>`头文件,但在新版本中,推荐使用`<iostream>`。C++程序在启动时会自动...
5. **I/O模型**:Mina使用了NIO(Non-blocking I/O)模型,该模型允许单个线程处理多个连接,提高了服务器的并发性能。与传统的BIO(Block I/O)相比,NIO在处理大量并发连接时更具优势。 6. **编码与解码**:在...
在Fortran中,流式I/O(Stream I/O)允许程序员以类似C++或C#的方式处理输入和输出。与传统的格式化I/O相比,流式I/O提供了一种更为灵活且易于理解的方法来处理文件。在描述中提到的`read_stream.f90`源代码文件,很...