当前位置:首页 C++ > 正文

C++中istream的使用

作者:野牛程序员:2024-10-22 08:10:56 C++阅读 1992
C++中istream的使用

istream 在 C++ 中用于处理输入流,主要用于从标准输入或文件中读取数据。使用时,通常通过 cin 对象或文件流对象创建实例。基本用法包括 >> 运算符进行数据读取和 getline() 函数读取整行文本。例如:

#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::string name;
    std::cout << "Enter your name: ";
    std::getline(std::cin, name); // 读取整行
    std::cout << "Hello, " << name << "!" << std::endl;

    std::ifstream file("data.txt");
    if (file.is_open()) {
        std::string line;
        while (std::getline(file, line)) {
            std::cout << line << std::endl; // 从文件读取行
        }
        file.close();
    }
    return 0;
}

以下是一些具体的示例,展示了如何在 C++ 中使用 istream 进行不同类型的数据输入。

示例 1:读取基本数据类型

#include <iostream>

int main() {
    int age;
    double height;

    std::cout << "Enter your age: ";
    std::cin >> age; // 读取整数
    std::cout << "Enter your height (in meters): ";
    std::cin >> height; // 读取浮点数

    std::cout << "You are " << age << " years old and " << height << " meters tall." << std::endl;

    return 0;
}

示例 2:读取字符串

使用 getline() 读取整行字符串,包括空格:

#include <iostream>
#include <string>

int main() {
    std::string fullName;

    std::cout << "Enter your full name: ";
    std::getline(std::cin, fullName); // 读取整行

    std::cout << "Welcome, " << fullName << "!" << std::endl;

    return 0;
}

示例 3:从文件中读取数据

从文件中读取多个数据项,可以使用 ifstream

#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::ifstream file("data.txt");
    if (!file) {
        std::cerr << "Unable to open file data.txt";
        return 1; // 返回错误
    }

    std::string name;
    int age;

    while (file >> name >> age) { // 逐行读取姓名和年龄
        std::cout << name << " is " << age << " years old." << std::endl;
    }

    file.close(); // 关闭文件
    return 0;
}

示例 4:处理输入错误

可以检查输入流的状态,以处理错误输入:

#include <iostream>

int main() {
    int number;

    std::cout << "Enter a number: ";
    while (!(std::cin >> number)) { // 检查输入是否有效
        std::cin.clear(); // 清除错误标志
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // 忽略错误输入
        std::cout << "Invalid input. Please enter a number: ";
    }

    std::cout << "You entered: " << number << std::endl;

    return 0;
}

这些示例展示了 istream 的不同用法,包括读取基本数据类型、字符串、从文件读取数据以及处理输入错误。


野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
  • C++
  • 最新推荐

    热门点击