P2 C++基础(2.2)
2.2 从 C 语言快速入门
2.2.1 输入输出
C++ 中的输入和输出( I/O )主要是通过标准库中的输入输出流来实现的。最常用的是 iostream 库,它提供了用于输入和输出的基本流类,包括 cin 、 cout 、 cerr 和 clog 。
标准输出流 ( cout )
cout 代表标准输出流,通常用于向屏幕输出数据。
使用操作符 << (插入操作符)向 cout 发送数据。
例如, std::cout << "Hello, world!" << std::endl; 会在屏幕上打印 "Hello, world!" 并换行。
标准输入流 ( cin )
cin 代表标准输入流,用于从键盘接收数据。
使用操作符 >> (提取操作符)从 cin 提取数据。
例如, int x; std::cin >> x; 会从用户那里读取一个整数并存储在变量 x 中。
标准错误流 ( cerr ) 和标准日志流 ( clog )
cerr 用于输出错误消息。与 cout 不同, cerr 不是缓冲的,这意味着它会立即输出。
clog 类似于 cerr ,但它是缓冲的。它通常用于记录错误和日志信息。
示例代码
下面是一个展示如何使用这些基本流的简单示例:
#include <iostream>
int main () {
// 使用 cout 输出
std::cout << "Enter a number: " ;
// 使用 cin 输入
int num ;
std::cin >> num ;
// 输出结果
std::cout << "You entered: " << num << std::endl ;
std::clog << "Logging: user entered a number." << std::endl ;
return 0 ;
}
2.2.2 基本变量类型
C++ 基本数据类型整理成表格。以下是一个表格,展示了不同的基本数据类型及其一般用途和大小范围: 和C 语言类似。

宽字符的用法
#include <iostream>
#include <locale>
#include <wchar.h>
int main () {
// 设置本地化以支持宽字符
std::setlocale ( LC_ALL , "" );
// 使用 wchar_t 类型定义一个宽字符串
wchar_t wstr [] = " 你好,世界! " ;
// 在 C++ 中打印宽字符串
std::wcout << wstr << std::endl ;
return 0 ;
}
在 C++ 中, <climits> (或在 C 中是 <limits.h> )是一个标准头文件,提供了关于整型限制的信
息。这个头文件中定义了各种整型数据类型的属性,如最大值、最小值等。使用这些信息可以帮助你了解在特定编译器和平台上各种数据类型的大小和范围。
如何使用 <climits>
要使用 <climits> 中定义的常量,你首先需要包含这个头文件:
然后,你可以使用它提供的各种常量,例如:
INT_MAX : int 类型的最大值。
INT_MIN : int 类型的最小值。
UINT_MAX : unsigned int 类型的最大值。
LONG_MAX : long int 类型的最大值。
LONG_MIN : long int 类型的最小值。
LLONG_MAX : long long int 类型的最大值。
LLONG_MIN : long long int 类型的最小值。
示例代码
下面是一个简单的示例,展示了如何使用 <climits> 中的值:
#include <iostream>
#include <climits>
int main () {
std::cout << "The range of int is from " << INT_MIN << " to " << INT_MAX <<
std::endl ;
std::cout << "The maximum value of unsigned int is " << UINT_MAX <<
std::endl ;
std::cout << "The range of long long is from " << LLONG_MIN << " to " <<
LLONG_MAX << std::endl ;
return 0 ;
}
这个程序会输出 int 、 unsigned int 和 long long int 类型的最大值和最小值。
注意事项
·<climits> 提供的是编译时确定的常量,这意味着这些值在编译时就已经固定,根据编译器和平台
的不同而可能有所不同。
·使用这些限制值可以帮助你编写更可移植和安全的代码,特别是在处理可能超出数据类型范围的操作时。