簡體   English   中英

C ++,fstream,從文件讀取未提供正確的結果

[英]C++, fstream, Reading from the file does not give correct result

我試圖創建一個簡單的程序,將輸入的數據寫入文件,然后從文件中讀取該數據。 由於某種原因,輸出不正確。 它從文件中讀取的第一個值顯示所有三個輸入值,而不僅僅是第一個。 有人可以告訴我我在做什么錯嗎?

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

using namespace std;


int main() {
    double totalRainfall=0.0, highTemperature,lowTemperature, totalHigh=0.0, 
     totalLow=0.0;

// open a file in write mode.
ofstream outFile;
outFile.open("statistics.txt");


    cout << "Enter total rainfall (in inches) : ";
    cin >> totalRainfall;
    outFile <<totalRainfall;  // write inputted data into the file.



    cout << "Enter high temperature (in Fahrenheit): ";
    cin >> highTemperature;
    outFile << highTemperature;  // write inputted data into the file.


    cout << "Enter low temperature (in Fahrenheit) : ";
    cin >> lowTemperature;
    outFile << lowTemperature;  // write inputted data into the file.

    //close the opened file
    outFile.close();

    //open a file in read mode.
    ifstream inFile;
    inFile.open("statistics.txt");

    inFile >> totalRainfall; 
    cout << "The rainfall: ";
    cout<< totalRainfall<<endl; 

    inFile >> highTemperature;
    cout << "High temperature: ";
    cout << highTemperature<<endl;

    inFile >> lowTemperature;
    cout << "Low temperature: ";
    cout<<lowTemperature<<endl;

    // close the opened file.
    inFile.close();

    system("pause");
    return 0;
}

您應該在每個輸出數字之間放置一個分隔符,以便在讀取文件時知道數字的開始位置和結束位置。 用作分隔符的空格字符允許讀取數字而無需特定代碼以跳過分隔符(讀取數字的STL函數將跳過前導空格字符)。

下面以空格作為分隔符的示例:

#include <fstream>
#include <iostream>

using namespace std;

const char sep = ' ';
const char* const file_path = "statistics.txt";

int main()
{
    double value = 0.0;

    ofstream outFile;
    outFile.open(file_path);

    cout << "Enter total rainfall (in inches): ";
    cin >> value;
    outFile << value << sep;

    cout << "Enter high temperature (in Fahrenheit): ";
    cin >> value;
    outFile << value << sep;

    cout << "Enter low temperature (in Fahrenheit): ";
    cin >> value;
    outFile << value;

    outFile.close();

    ifstream inFile;
    inFile.open(file_path);

    inFile >> value;
    cout << "The rainfall: ";
    cout << value << endl;

    inFile >> value;
    cout << "High temperature: ";
    cout << value << endl;

    inFile >> value;
    cout << "Low temperature: ";
    cout << value << endl;

    return 0;
}

您應該使用fstream對象的write()read()方法。 這些方法允許您寫入/讀取特定數量的字節。 因此,您可以只創建兩個實用程序函數,如下所示:

void writeValue(ofstream& f, const double& v) {
    f.write(reinterpret_cast<const char*>(&v), sizeof(v));
}

void readValue(ifstream& f, double& v) {
    f.read(reinterpret_cast<char*>(&v), sizeof(v));
}

現在,您可以在主要代碼中使用它們:

double value = 0.0;

ofstream outFile;
outFile.open(file_path);

cout << "Enter total rainfall (in inches): ";
cin >> value;
writeValue(outFile, value);

cout << "Enter high temperature (in Fahrenheit): ";
cin >> value;
writeValue(outFile, value);

cout << "Enter low temperature (in Fahrenheit): ";
cin >> value;
writeValue(outFile, value);

outFile.close();

ifstream inFile;
inFile.open(file_path);

readValue(inFile, value);
cout << "The rainfall: ";
cout << value << endl;

readValue(inFile, value);
cout << "High temperature: ";
cout << value << endl;

readValue(inFile, value);
cout << "Low temperature: ";
cout << value << endl;

改善讀寫功能

我上面提到的實用程序功能只能處理double值。 這不靈活,如果您想擴展代碼並處理不同類型的信息,就應該成為一個問題。 因此,如果您想使代碼更健壯並在序列化文件中允許其他變量類型(例如,int,float),則可以使用模板代替:

template<typename T>
void writeValue(ofstream& f, const T& v) {
    f.write(reinterpret_cast<const char*>(&v), sizeof(v));
}

template<typename T>
constexpr void readValue(ifstream& f, T& v) {
    f.read(reinterpret_cast<char*>(&v), sizeof(v));
}

如果您還想處理std::string ,則可以為該特定類型自定義模板:

template<>
constexpr void writeValue(ofstream& f, const std::string& v) {
    auto len = v.length();
    f.write(reinterpret_cast<const char*>(&len), sizeof(len));
    f.write(v.c_str(), v.length() * sizeof(char));
}

template<>
void readValue(ifstream& f, std::string& v) {
    std::string::size_type len;
    f.read(reinterpret_cast<char *>(&len), sizeof(len));

    char buffer[len + 1];
    f.read(buffer, len);
    buffer[len] = '\0';
    v = buffer;
}

暫無
暫無

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

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