c++ - 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;
}
解决方案
您应该在每个输出数字之间放置一个分隔符,以便在读取文件时能够知道数字的开始位置和结束位置。空白字符作为分隔符允许在没有特定代码的情况下读取数字以跳过分隔符(读取数字的 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;
}
推荐阅读
- c++ - 在 C++ 源文件中每个函数定义的开头添加一个宏调用
- assembly - 如果 64 位架构中不存在 LDT,那么使用它的 32 位系统如何在 64 位架构上进行仿真?
- entity-framework-core - EF Core 3.0 Linq 十进制比较(大于或小于)不起作用 - 无法翻译
- node.js - Nodejs与分子微服务应用程序,如何保持运行服务器
- java - 为什么使用帖子上传文件后页面会重新加载?(角+弹簧启动)
- flutter - 用户 NavigatorState 清除所有路由并推送主路由
- node.js - 我可以在同一个 express 框架中为多个用户模式使用 Passport JWT
- svelte - Svelte dev server is stuck on old version
- html - Visual Studio 调试错误“错误处理启动:错误:无法附加到主目标
- python - Pandas Groupby、Sum 和 Flatten Dataframe