[英]Do you have to write the type of a variable declared in a header file in a C++ file?
[英]How do you output variable's declared as a double to a text file in C++
我是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;
}
所以我想做的是使用這些變量並將其輸出到文本文件。 另外,請告知我需要用於此源代碼的includes。 也請隨時提出有關如何以其他方式改進我的代碼的建議。
提前致謝。
正如您的標記所建議的,您使用文件流:
std::ofstream ofs("/path/to/file.txt");
ofs << amtDueIn20;
根據所需文件的不同,您可能必須編寫更多內容(例如空格等)才能獲得不錯的格式。
由於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;
}
為我編譯(VC9)並將其寫入test.txt
:
3.14159
你能試試嗎?
只需使用流寫操作符operator <<,它具有一個重載的double定義(在basic_ostream中定義)
#include <fstream>
...
std::fstream stmMyStream( "c:\\tmp\\teststm.txt", std::ios::in | std::ios::out | std::ios::trunc );
double dbMyDouble = 23.456;
stmMyStream << "The value is: " << dbMyDouble;
要回答第一個問題,請在C語言中使用printf(對於文件輸出fprintf)。 IIRC,cout也具有大量的修飾符,但是正如您最初提到的fstream(比C ++更為“ C”為中心),我不會提及它們-
糟糕,錯過了ofstream指標,請忽略我的“ C”注釋並使用C ++
為了改進您的程序,請確保在進行上述計算時使用很多括號,以確保100%按照您希望的方式評估事物(不依賴優先級)
一般來說,寫入輸出的方法是printf,wprintf等。
對於文件,這些方法被命名為fprintf_s,fsprintf_s等。
請注意,“ _ s”方法是先前格式化方法的新安全變體。 您應該始終使用這些新的安全版本。
有關示例,請參考: http : //msdn.microsoft.com/zh-cn/library/ksf1fzyy%28VS.80%29.aspx
請注意,這些方法使用格式說明符將給定類型轉換為文本。 例如,%d充當整數的占位符。 同樣,%f代表double。
只需在輸出流上使用<<
操作符:
#include <fstream>
int main() {
double myNumber = 42.5;
std::fstream outfile("test.txt", std::fstream::out);
outfile << "The answer is almost " << myNumber << std::endl;
outfile.close();
}
我遇到了完全相同的問題,ofstream在哪里輸出字符串,但是一旦到達變量就停止了。 通過更多谷歌搜索,我在一個論壇帖子中找到了該解決方案:
在Xcode 3.2下,基於stdc ++項目模板創建新項目時,調試配置的目標構建設置會添加與gcc-4.2不兼容的預處理器宏:_GLIBCXX_DEBUG = 1 _GLIBXX_DEBUG_PEDANTIC = 1
如果要使Debug / gcc-4.2正確執行,請銷毀它們。
http://forums.macrumors.com/showpost.php?p=8590820&postcount=8
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.