[英]C++ problem with string stream istringstream
I am reading a file in the following format 我正在读取以下格式的文件
1001 16000 300 12.50
2002 24000 360 10.50
3003 30000 300 9.50
where the items are: loan id, principal, months, interest rate. 这些项目是:贷款ID,本金,月份,利率。
I'm not sure what it is that I am doing wrong with my input string stream, but I am not reading the values correctly because only the loan id is read correctly. 我不确定输入字符串流做错了什么,但是我无法正确读取值,因为只能正确读取贷款ID。 Everything else is zero.
其他所有内容均为零。 Sorry this is a homework, but I just wanted to know if you could help me identify my error.
抱歉,这是一项作业,但我只是想知道您是否可以帮助我确定我的错误。
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;
}
}
You are not reading linewise. 您不是按行阅读的。 Replace the condition by
替换条件为
while( getline(inputstream, line) )
If you use operator>>
it will extract only the first word to line
. 如果您使用
operator>>
,它将仅提取第一个单词到line
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.