use*_*427 2 c++ fstream iostream
我是C++的新手,我想知道如何输出/写入声明为double的变量到txt文件.我知道如何使用fstream输出字符串,但我无法弄清楚如何发送任何其他内容.我开始认为你不能发送任何东西,但字符串到文本文件是正确的吗?如果是这样,那么如何将存储在变量中的信息转换为字符串变量?
这是我的代码,我正在尝试实现这个概念,它相当简单:
int main()
{
double invoiceAmt = 3800.00;
double apr = 18.5; //percentage
//compute cash discount
double discountRate = 3.0; //percentage
double discountAmt;
discountAmt = invoiceAmt * discountRate/100;
//compute amount due in 10 days
double amtDueIn10;
amtDueIn10 = invoiceAmt - discountAmt;
//Compute Interest on the loan of amount (with discount)for 20 days
double LoanInt;
LoanInt = amtDueIn10 * (apr /360/100) * 20;
//Compute amount due in 20 days at 18.5%.
double amtDueIn20;
amtDueIn20 = invoiceAmt * (1 + (apr /360/100) * 20);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
所以我要做的就是使用这些变量并将它们输出到文本文件中.另外,请告知我需要用于此源代码的包含.请随意提供有关如何以其他方式改进我的代码的建议.
提前致谢.
正如您的标记所示,您使用文件流:
std::ofstream ofs("/path/to/file.txt");
ofs << amtDueIn20;
Run Code Online (Sandbox Code Playgroud)
根据您需要的文件,您可能需要编写更多内容(如空格等)以获得合适的格式.
编辑由于rmagoteaux22的持续问题:
这段代码
#include <iostream>
#include <fstream>
const double d = 3.1415926;
int main(){
std::ofstream ofs("test.txt");
if( !ofs.good() ) {
std::cerr << "Couldn't open text file!\n";
return 1;
}
ofs << d << '\n';
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为我编译(VC9)并将其写入test.txt:
3.14159
Run Code Online (Sandbox Code Playgroud)
你能试试吗?