首页 > 解决方案 > C++,fstream,从文件中读取没有给出正确的结果

问题描述

我正在尝试创建一个简单的程序,将输入的数据写入文件,然后从文件中读取该数据。由于某种原因,输出不正确。它从文件中读取的第一个值显示所有三个输入值,而不仅仅是第一个。有人可以告诉我我做错了什么吗?

#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;
}

标签: c++fstreamifstreamofstream

解决方案


您应该在每个输出数字之间放置一个分隔符,以便在读取文件时能够知道数字的开始位置和结束位置。空白字符作为分隔符允许在没有特定代码的情况下读取数字以跳过分隔符(读取数字的 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;
}

推荐阅读