【发布时间】:2014-06-05 09:11:40
【问题描述】:
大家早上好。
我开始学习 c++,我正在尝试制作一个可以从一种货币转换为另一种货币的 prog。
我创建了一个文本文件“currency.txt”,其中包含所有货币,一个接一个,每个有 4 行:
国家、货币描述、货币代码、汇率。
到目前为止,我编写了以下代码:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
struct currency {
string country;
string coin;
string code;
double rate;
};
int count_lines ( ifstream &myfile ){
string line;
int lines = 0;
if ( myfile.is_open() ){
while ( getline( myfile, line ) ){
++lines;
}
} else cout << "error";
myfile.seekg (0, ios::beg);
return lines;
}
void read_coins ( currency coins[], ifstream &myfile, int lines) {
string line;
if ( myfile.is_open() ){
for ( int n=0; n<lines; n++){
getline( myfile, line );
coins[n].country = line;
getline( myfile, line );
coins[n].coin = line;
getline( myfile, line );
coins[n].code = line;
getline( myfile, line );
stringstream(line) >> coins[n].rate;
}
} else cout << "error";
myfile.seekg (0, ios::beg);
}
int main(){
ifstream myfile ( "currency.txt" );
int lines;
lines = count_lines ( myfile )/4;
currency coins [lines];
read_coins (coins, myfile, lines);
for (int n=0; n<lines; n++){
cout << coins[n].country << '\t';
cout << coins[n].coin << '\t';
cout << coins[n].code << '\t';
cout << coins[n].rate << endl;
}
myfile.close ();
return 0;
}
但它只是不工作。如果我在所有功能中打开文件,它可以工作,但不是这样。 我知道肯定有问题,但我还是想不通。
还有一个问题:汇率有 10 位小数,但是当我把它放在我的硬币 [n].rate 中时,它只有 5 或 6 位小数。反正有10个都可以吗?
有人可以帮帮我吗?
谢谢
【问题讨论】:
-
你能详细说明什么不起作用。
-
你读到文件末尾,然后寻找开头但不清除流状态,所以我怀疑文件结束标志仍然设置。尝试在
seekg之前、之前或之后调用myfile.clear()。#include <iomanip>然后使用std::setprecision请求显示浮点输出的特定精度。 -
感谢@TonyD。这确实是问题所在! molbdnilo 也给出了这样的解释!
-
你为什么不调试你的代码而不是问我们?
-
@sashoalm:我在打扰吗?如果是这样,我很抱歉。如果你看到我帖子的开头,我清楚地说我开始学习了。如果我还不知道如何做所有事情,例如调试,我真的很抱歉。但别担心。我会学习的。