簡體   English   中英

C ++從txt文件中的兩列讀取和存儲變量

[英]C++ Read and store variables from two columns in a txt file

我目前正在嘗試為我的 C++ 類創建一個代表高溫和低溫的燭台圖。 在此作業中,我們提供了一個 txt 文件,其中包含以下格式的兩個數據列:

平均每月低高溫 (F)

XY

XY

XY

我已成功讀取 txt 文件,但對如何選擇特定數據感到困惑。 我想基本上跳過第一句話並存儲其余變量以創建圖形。 這就是我遇到的麻煩。

最后,我需要顯示文本文件的第一行,以及顯示圖形。 我非常希望得到你的幫助。

如果有更有效的方法來做到這一點,我很想了解更多!

你應該把大問題分解成小問題,然后先解決最小的問題。 此外,您應該使用 buildinC++ 功能。 An,在 C++ 中,您應該使用面向對象的方法。

這意味着,將數據及其相關功能存儲在一個對象中。 因此,數據和方法,對這些數據進行操作。

我建議構建 2 個類(或結構)。 On 保持只有一對低溫和高溫。

第二個類,包含標題行和一個低-高溫對的列表(實現為std::vector )。

在我們的示例中,我們需要的方法是從流中提取和插入。

為此,我們使用眾所周知的運算符<<>>並將它們添加到我們的類中。 在這里,我們將執行所有必要的 IO 操作。

因此,如果我們按照上述方法將大問題拆分為較小的部分,那么我們將獲得更易於理解和可讀性更好的代碼。

最后但並非最不重要的一點是,我們將使用標准庫中的現有函數,例如std::copy

istream_iteratorstd::ostream_iterator將簡單地調用底層的提取操作符>>和插入操作符<<

完整程序的示例(許多可能的解決方案之一)可以在下面看到:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>

// A data struct that can hold a low and a high temperatur and knows, how reaad and write its data
struct LowHighTemperature {

    // The data
    double low{};
    double high{};

    // The extractor operator for reading values from a stream
    friend std::istream& operator >> (std::istream& is, LowHighTemperature& lht) {
        return is >> lht.low >> lht.high;
    }
    // The inserter operator for writing values to a stream
    friend std::ostream& operator << (std::ostream& os, const LowHighTemperature& lht) {
        return os << lht.low << '\t' << lht.high;
    }
};

// A list with high and low temperatures and a header line
struct TemperatureList {
    // The data
    std::string header{};
    std::vector<LowHighTemperature> lowHighTemperature{};

    // The extractor operator for reading values from a stream
    friend std::istream& operator >> (std::istream& is, TemperatureList& tl) {

        // Delete potentioally pre existing data
        tl.lowHighTemperature.clear();
        // Read the header line
        if (std::getline(is, tl.header))
            // Now read all temperatures
            std::copy(std::istream_iterator<LowHighTemperature>(is), {}, std::back_inserter(tl.lowHighTemperature));
        return is;
    }
    // The inserter operator for writing values to a stream
    friend std::ostream& operator << (std::ostream& os, const TemperatureList& tl) {
        // Show header
        os << tl.header << '\n';
        // Show temperatures
        std::copy(tl.lowHighTemperature.begin(), tl.lowHighTemperature.end(), std::ostream_iterator<LowHighTemperature>(os, "\n"));
        return os;
    }
};


// Please store the path to your temperatures source file here
const std::string temperatureFileName{ "r:\\temperatures.txt" };

int main() {

    // Open source file and check, if it is open
    if (std::ifstream temperaturFileStream{ temperatureFileName }; temperaturFileStream) {

        // Here we will store the list with all temperatures and the header
        TemperatureList temperatureList{};

        // Read all data from file stream
        temperaturFileStream >> temperatureList;

        // For debug purposes, you show the result on the screen
        std::cout << temperatureList;
    }
    else {
        std::cerr << "\n\nError: Could not open '" << temperatureFileName << "'\n";
    }
    return 0;
}

您可以添加您自己計算所需的任何其他方法。

您可以通過temperatureList.lowHighTemperature[0]訪問第一個溫度對

我希望你有這個想法。

您使用std::getline()閱讀 C++ 中的一行。 請注意,檢查所有輸入函數的返回值以檢測錯誤或丟失的數據或媒體問題等是一種很好的做法。 getline()以及輸入operator>>()返回輸入流。 Streams 有一個很方便的 bool 轉換:當遇到錯誤(讀​​取錯誤,文件結束)時,轉換結果為false 如果流正常,則為 true。 這種具有這些語義的轉換經過精心設計,以便於檢查輸入操作是否成功:

std::string header;
if(!std::getline(infile, header)) { 
    std::cerr << "Couldn't read first line\n"; 
    exit(1); 
}
// keep line for later output. 
// Now read the number pairs. The numbers must be pairs but they actually don't
// have to be on a single line (but it doesn't hurt either).

int a, b;
// The read could fail for other reasons as well; 
// a more robust program would look at the status bits of the stream
// and, if an error occurred, print an error message.
while (infile >> a >> b) { // will be false when EOF is reached
{
    // print your tree or whatever
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM