C++ 使用 iostream
库提供的 cout
(输出)和 cin
(输入),而 C 语言使用 stdio.h
的 printf/scanf
。下面我们从基础语法、类型安全、易用性三个方面对比,并编写第一个 C++ 程序。
**📌 1. C++ 风格:cout
和 cin
**
代码示例
#include <iostream> // C++标准输入输出库
using namespace std; // 使用std命名空间(避免写std::cout)
int main() {
int age;
string name;
cout << "Enter your name: "; // 输出提示
cin >> name; // 输入字符串(无空格)
cout << "Enter your age: ";
cin >> age;
cout << "Hello, " << name << "! You are " << age << " years old." << endl;
return 0;
}
**✅ 优点:**
- 类型安全:
cin/cout
自动识别变量类型(无需%d
、%s
等格式符)。 - 链式调用:
<<
和>>
可连续使用(如cout << a << b;
)。 - 更易读:接近自然语言(
cout << "Hello"
比printf("Hello")
更直观)。
**⚠️ 注意:**
cin
遇到空格会停止输入(如输入"John Doe"
只会读取"John"
)。- 如果要读取整行(含空格),用
getline(cin, str)
。
**📌 2. C 风格:printf
和 scanf
**
代码示例
#include <stdio.h> // C标准输入输出库
int main() {
int age;
char name[50]; // C风格字符串(字符数组)
printf("Enter your name: ");
scanf("%s", name); // %s 读取字符串(无空格)
printf("Enter your age: ");
scanf("%d", &age); // %d 读取整数,& 取地址
printf("Hello, %s! You are %d years old.\n", name, age);
return 0;
}
**✅ 优点:**
- 更底层:适合需要精细控制格式的场景(如
%5.2f
控制浮点数显示)。 - 性能略高:某些情况下比
cout
更快(但现代编译器优化后差距很小)。
**⚠️ 缺点:**
- 不安全:
scanf
可能缓冲区溢出(如char[5]
但输入"ABCDEF"
)。 - 繁琐:必须手动指定格式(如
%d
、%s
),写错会导致未定义行为。
🆚 3. 关键对比
特性 | C++ (cin/cout ) | C (scanf/printf ) |
---|---|---|
头文件 | <iostream> | <stdio.h> |
输入方式 | cin >> var | scanf("%d", &var) |
输出方式 | cout << "Hello" | printf("Hello") |
类型安全 | ✅ 自动识别类型 | ❌ 需手动匹配格式符(如 %d ) |
字符串处理 | string 类(动态大小) | char[] 数组(固定大小,易溢出) |
扩展性 | 支持自定义类型的 << 和 >> | 仅支持基本类型 |
🚀 4. 何时用哪种?
- 优先用 C++ (
cin/cout
):- 写 C++ 程序时默认使用(更安全、更现代)。
- 需要处理
string
类或自定义类型时。
- 用 C (
printf/scanf
):- 需要精确控制格式(如
%8.3f
对齐浮点数)。 - 在嵌入式/C遗留代码中维护时。
- 需要精确控制格式(如
🔧 5. 常见问题
Q1:cin
和 scanf
混用会出问题吗?
会! 例如:
int age;
string name;
cin >> age; // 输入 "20\n"
getline(cin, name); // 读取到的是 "\n",而不是下一行!
**✅ 解决方法**:
在 cin >>
后加 cin.ignore()
清除缓冲区:
cin >> age;
cin.ignore(); // 忽略残留的换行符
getline(cin, name); // 现在能正常读取
Q2:cout
如何控制格式(如保留小数)?
用 <iomanip>
库:
#include <iomanip>
double pi = 3.1415926;
cout << fixed << setprecision(2) << pi; // 输出 "3.14"
**✏️ 6. 练习**
- 用
cin/cout
编写程序:输入圆的半径,计算并输出面积(π=3.14)。 - 用
scanf/printf
实现相同功能,对比两者的代码风格。
参考答案
// C++ 版
#include <iostream>
using namespace std;
int main() {
double radius;
cout << "Enter radius: ";
cin >> radius;
cout << "Area = " << 3.14 * radius * radius << endl;
return 0;
}
// C 版
#include <stdio.h>
int main() {
double radius;
printf("Enter radius: ");
scanf("%lf", &radius);
printf("Area = %.2f\n", 3.14 * radius * radius);
return 0;
}