溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C++流庫函數(shù)應用實例

發(fā)布時間:2024-09-10 12:35:37 來源:億速云 閱讀:79 作者:小樊 欄目:編程語言

C++ 流庫(iostream)是一個功能強大的輸入/輸出庫,它提供了格式化輸入/輸出功能,支持各種數(shù)據(jù)類型

  1. 從鍵盤讀取整數(shù)和字符串:
#include<iostream>
#include<string>

int main() {
    int age;
    std::string name;

    std::cout << "Enter your name: ";
    std::cin >> name;

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

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

    return 0;
}
  1. 從文件讀取數(shù)據(jù)并計算平均值:
#include<iostream>
#include <fstream>
#include<vector>

int main() {
    std::ifstream input_file("data.txt");
    std::vector<double> numbers;
    double number;

    if (!input_file) {
        std::cerr << "Error opening file."<< std::endl;
        return 1;
    }

    while (input_file >> number) {
        numbers.push_back(number);
    }

    input_file.close();

    double sum = 0;
    for (const auto &num : numbers) {
        sum += num;
    }

    double average = sum / numbers.size();
    std::cout << "The average of the numbers in the file is: "<< average<< std::endl;

    return 0;
}
  1. 將數(shù)據(jù)寫入文件:
#include<iostream>
#include <fstream>

int main() {
    std::ofstream output_file("output.txt");

    if (!output_file) {
        std::cerr << "Error opening file."<< std::endl;
        return 1;
    }

    std::string text = "Hello, World!";
    output_file<< text<< std::endl;

    output_file.close();

    std::cout << "Text has been written to the file."<< std::endl;

    return 0;
}

這些實例展示了 C++ 流庫的基本用法。你可以根據(jù)需要修改和擴展這些代碼以滿足你的需求。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

c++
AI