【问题标题】:can't fill an array using a file无法使用文件填充数组
【发布时间】: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 &lt;iomanip&gt; 然后使用 std::setprecision 请求显示浮点输出的特定精度。
  • 感谢@TonyD。这确实是问题所在! molbdnilo 也给出了这样的解释!
  • 你为什么不调试你的代码而不是问我们?
  • @sashoalm:我在打扰吗?如果是这样,我很抱歉。如果你看到我帖子的开头,我清楚地说我开始学习了。如果我还不知道如何做所有事情,例如调试,我真的很抱歉。但别担心。我会学习的。

标签: c++ arrays file


【解决方案1】:

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

在搜索开始之前添加myfile.clear()

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

添加

 #include <iomanip>

std::cout << std::setprecision(10);

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

【讨论】:

  • 感谢您的回答!我正在使用代码块,但不知道 c++ 的版本是什么。我会试试你的建议。
  • 效果很好!!!不知道 seekg 不会重置文件结束标志。非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-28
  • 1970-01-01
  • 2018-07-05
  • 2015-02-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多