无法使用文件填充数组

can't fill an array using a file

本文关键字:填充 数组 文件      更新时间:2023-10-16

大家早上好

我开始学习c++,我正在尝试制作一个程序,从一种货币转换到另一种。

我创建了一个文本文件"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]里。速率,它只有5到6个十进制数字。有办法把所有10个都取下来吗?

有人能帮我一下吗?

谢谢

如果您不使用c++ 11, seekg不会重置文件的文件结束状态。

在开始查找前添加myfile.clear()

浮点数的输出取决于当前流的精度。
默认值为6(6)。

添加
 #include <iomanip>

std::cout << std::setprecision(10);
输出前


(但请记住,浮点数本身是不精确的,因此您不一定会得到与文件中完全相同的数字—只需尽可能接近的数字。)