在 C++ 的文本文件中保存多个输出
Saving multiple output in a text file in c++
仍在尝试学习 c++。我们的教授希望我们制作一个程序,其中温度的输出将保存在文本文件中。可变结果是我要保存的输出。尽管代码有效并保存了结果,但问题是它只保存了第一个结果。我设置了一个限制,现在我只想保存至少 5 个结果。
#include <iostream>
#include <stdlib.h>
#include <fstream>
using namespace std;
int main()
{
double value, the_result, result;
int choice;
ofstream file;
file.open("output.txt");
do {
cout <<"nnChoose among the following:"
"n1 = Celsius to Fahrenheit"
"n2 = Celsius to Kelvin"
"n3 = Fahrenheit to Celsius"
"n4 = Fahrenheit to Kelvin"
"n5 = Kelvin to Celsius"
"n6 = Kelvin to Fahrenheit"
"n7 = Exit"
"nnChoice:n";
cin >> choice;
switch (choice){
case 1:
cout<<"Enter Value"<< endl;
if (!(cin >> value )){
cout << "Invalid Input. Please Try Again!!";
cin.clear();
cin.ignore(123, 'n');
}else{
result = value*9/5+32;
cout <<"The result is ~"<< result << "370";
}
break;
case 2:
cout<<"Enter Value"<< endl;
if (!(cin >> value )){
cout << "Invalid Input. Please Try Again!!";
cin.clear();
cin.ignore(123, 'n');
}else{
result = value+273.15;
cout <<"The result is ~"<< result << "K";
}
break;
case 3:
cout<<"Enter Value"<< endl;
if (!(cin >> value )){
cout << "Invalid Input. Please Try Again!!";
cin.clear();
cin.ignore(123, 'n');
}else{
the_result = value-32;
result = the_result*5/9;
cout <<"The result is ~"<< result << "370" << "F";
}
break;
case 4:
cout<<"Enter Value"<< endl;
if (!(cin >> value )){
cout << "Invalid Input. Please Try Again!!";
cin.clear();
cin.ignore(123, 'n');
}else{
the_result = value + 459.67;
result = the_result*5/9;
cout <<"The result is ~"<< result << "K";
}
break;
case 5:
cout<<"Enter Value"<< endl;
if (!(cin >> value )){
cout << "Invalid Input. Please Try Again!!";
cin.clear();
cin.ignore(123, 'n');
}else{
result = value - 273.15;
cout <<"The result is ~"<< result << "370";
}
break;
case 6:
cout<<"Enter Value"<< endl;
if (!(cin >> value )){
cout << "Invalid Input. Please Try Again!!";
cin.clear();
cin.ignore(123, 'n');
}else{
result = value*9/5-459.67;
cout <<"The result is ~"<< result << "370" << "F";
}
break;
case 7:
return EXIT_SUCCESS;
break;
}
for (double i=0; i<5; i++){
file << result<< endl;
}
file.close();
}
while (choice !=7);
}
只是为了扩展AProgrammer的评论 - 问题是在第一次迭代之后,您尝试写入已经关闭且未重新打开的文件。因此,按照建议,您应该将file.close()
移动到 do while 循环之外
相关文章:
- 我将如何保存此 for 循环的输出
- 在 C++ 的文本文件中保存多个输出
- 如何以C++格式输出已保存.html文件中<a href>标签中的所有链接?
- 创建一个动态数组,包括汽车的年份和品牌,但无法保存我的第一个输出
- 文件不会将输出保存到文件中,并在 Linux C++奇怪地打印出一个字符串
- 将所有控制台输出数据保存到新的文本文件C++
- 如何将输出从终端保存到变量
- 在 C++ 中将编辑过的内文件保存到输出文件时出现问题
- 使用Borland C++执行dos命令并保存输出
- C++ 在退出 WINAPI 之前将控制台输出保存到文本文件(无 MFC)
- 旋转纹理 sfml 并将输出保存到文件
- 使用十六进制保存输出会增加空格
- c++将输出(数字)保存到一个数组中.一次两个数字
- 在运行时保存服务的输出
- 我如何在windows中获得PyErr_Print的输出或将其保存为字符串?
- 从.txt读取int,将其保存到vector,然后保存到输出文件
- c++ Qt和WinExec -保存CMD输出文件在特定的文件夹
- 使用FMOD将输出保存到磁盘
- 如何将C++控制台输出保存在文本文件中
- 使用 openCV c++ 示例代码执行抓取后保存输出图像