[英]C++ problem with string stream istringstream
我正在讀取以下格式的文件
1001 16000 300 12.50
2002 24000 360 10.50
3003 30000 300 9.50
這些項目是:貸款ID,本金,月份,利率。
我不確定輸入字符串流做錯了什么,但是我無法正確讀取值,因為只能正確讀取貸款ID。 其他所有內容均為零。 抱歉,這是一項作業,但我只是想知道您是否可以幫助我確定我的錯誤。
if( inputstream.is_open() ){
/** print the results **/
cout << fixed << showpoint << setprecision(2);
cout << "ID " << "\tPrincipal" << "\tDuration" << "\tInterest" << "\tPayment" <<"\tTotal Payment" << endl;
cout << "---------------------------------------------------------------------------------------------" << endl;
/** assign line read while we haven't reached end of file **/
string line;
istringstream instream;
while( inputstream >> line ){
instream.clear();
instream.str(line);
/** assing values **/
instream >> loanid >> principal >> duration >> interest;
/** compute monthly payment **/
double ratem = interest / 1200.0;
double expm = (1.0 + ratem);
payment = (ratem * pow(expm, duration) * principal) / (pow(expm, duration) - 1.0);
/** computer total payment **/
totalPayment = payment * duration;
/** print out calculations **/
cout << loanid << "\t$" << principal <<"\t" << duration << "mo" << "\t" << interest << "\t$" << payment << "\t$" << totalPayment << endl;
}
}
您不是按行閱讀的。 替換條件為
while( getline(inputstream, line) )
如果您使用operator>>
,它將僅提取第一個單詞到line
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.