跳转至

C++ 编程入门 - Day 1

引言

在今天的学习中,我们将深入探索 C++ 标准库中的 <iostream> 头文件。这是 C++ 编程中最基础也是最重要的部分之一,它提供了输入和输出功能,使我们的程序能够与用户进行交互。


1. <iostream> 详细介绍

<iostream> 是 C++ 标准库中用于输入和输出操作的核心头文件。它定义了一组类和对象,用于处理控制台输入和输出。

主要组件:

  1. cout - 标准输出流,用于向控制台输出数据
  2. cin - 标准输入流,用于从控制台读取数据
  3. cerr - 标准错误流,用于输出错误信息
  4. clog - 标准日志流,用于输出日志信息

输出流操作:

#include <iostream>

using namespace std;

int main() {
    cout << "Hello World!" << endl;
    cout << "This is a test." << endl;

    // 输出不同类型的数据
    int age = 25;
    double height = 1.75;
    cout << "Age: " << age << ", Height: " << height << endl;

    return 0;
}

输入流操作:

#include <iostream>
#include <string>

using namespace std;

int main() {
    string name;
    int age;

    cout << "Please enter your name: ";
    getline(cin, name); // 读取整行输入

    cout << "Please enter your age: ";
    cin >> age;

    cout << "Hello, " << name << "! You are " << age << " years old." << endl;

    return 0;
}

2. 经典示例

示例 1:简单的计算器

#include <iostream>

using namespace std;

int main() {
    double num1, num2;
    char op;

    cout << "Enter first number: ";
    cin >> num1;

    cout << "Enter operator (+, -, *, /): ";
    cin >> op;

    cout << "Enter second number: ";
    cin >> num2;

    double result;

    switch(op) {
        case '+':
            result = num1 + num2;
            break;
        case '-':
            result = num1 - num2;
            break;
        case '*':
            result = num1 * num2;
            break;
        case '/':
            if(num2 != 0) {
                result = num1 / num2;
            } else {
                cout << "Error: Division by zero!" << endl;
                return 1;
            }
            break;
        default:
            cout << "Error: Invalid operator!" << endl;
            return 1;
    }

    cout << "Result: " << num1 << " " << op << " " << num2 << " = " << result << endl;

    return 0;
}

示例 2:猜数字游戏

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main() {
    srand(time(0)); // 初始化随机数生成器
    int secretNumber = rand() % 100 + 1; // 生成1-100之间的随机数
    int guess;
    int attempts = 0;

    cout << "Welcome to the Number Guessing Game!" << endl;
    cout << "I'm thinking of a number between 1 and 100." << endl;

    do {
        cout << "Enter your guess: ";
        cin >> guess;
        attempts++;

        if(guess > secretNumber) {
            cout << "Too high!" << endl;
        } else if(guess < secretNumber) {
            cout << "Too low!" << endl;
        } else {
            cout << "Congratulations! You guessed the number in " << attempts << " attempts!" << endl;
        }
    } while(guess != secretNumber);

    return 0;
}

3. 常见的问题和回答

问题 1:std::endl"\n" 的区别

std::endl"\n" 都可以用来在输出中换行,但它们有一些重要的区别:

  1. std::endl
  2. 插入换行符
  3. 刷新输出缓冲区
  4. 使用方式:cout << "Hello" << endl;
  5. 性能稍差,因为会强制刷新缓冲区

  6. "\n"

  7. 只插入换行符
  8. 不刷新输出缓冲区
  9. 使用方式:cout << "Hello\n";
  10. 性能更好

最佳实践:在大多数情况下,使用 "\n" 更高效。只有在需要确保输出立即显示时(如在调试时),才需要使用 std::endl

问题 2:如何处理错误输入?

当使用 cin 读取数据时,如果用户输入了不符合预期格式的数据,会导致输入失败。我们可以使用 cin.fail() 来检测输入错误,并使用 cin.clear()cin.ignore() 来恢复输入流。

#include <iostream>

using namespace std;

int main() {
    int age;

    cout << "Enter your age: ";
    cin >> age;

    if(cin.fail()) {
        cout << "Invalid input!" << endl;
        cin.clear(); // 清除错误状态
        cin.ignore(1000, '\n'); // 忽略输入缓冲区中的剩余字符
    } else {
        cout << "Your age is: " << age << endl;
    }

    return 0;
}

问题 3:如何使用 getline()cin 一起工作?

当使用 cin >> 读取数据后,输入缓冲区中会留下换行符。如果接下来使用 getline(),它会立即读取到这个换行符,导致读取失败。我们可以使用 cin.ignore() 来解决这个问题。

#include <iostream>
#include <string>

using namespace std;

int main() {
    int age;
    string name;

    cout << "Enter your age: ";
    cin >> age;
    cin.ignore(); // 忽略换行符

    cout << "Enter your name: ";
    getline(cin, name);

    cout << "Hello, " << name << "! You are " << age << " years old." << endl;

    return 0;
}

总结

在今天的学习中,我们深入探索了 C++ 标准库中的 <iostream> 头文件。我们学习了:

  1. <iostream> 的基本概念和主要组件
  2. 如何使用 cout 进行输出操作
  3. 如何使用 cingetline() 进行输入操作
  4. 两个经典示例程序:简单的计算器和猜数字游戏
  5. 常见问题的解答,包括 std::endl"\n" 的区别

这些知识是 C++ 编程的基础,我们将在未来的学习中继续探索更多高级功能。


练习建议: 1. 尝试修改计算器程序,添加更多操作,如求幂、取模等 2. 改进猜数字游戏,添加提示功能(如"太大"或"太小") 3. 编写一个程序,读取用户的姓名、年龄和地址,并格式化输出