无法使用文件填充数组
can't fill an array using a file
大家早上好
我开始学习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);
输出前。
(但请记住,浮点数本身是不精确的,因此您不一定会得到与文件中完全相同的数字—只需尽可能接近的数字。)
相关文章:
- C++ 填充数组时遇到问题
- 如何使用同时设置计数和填充数组的函数
- 如何使填充数组的函数发送到函数?而不是其参数中的数组
- 如何使用文件填充数组并将其与用户输入C 进行比较
- 使用 memset 填充数组会显示垃圾
- Visual Studio从文件中填充数组时中断
- 分段 填充数组时出错
- 用不同的值填充数组/矢量的边缘和中心
- 使用相同的数据填充数组对象或使用指针
- 是否可以使用三元运算符"?"在 C/C++ 中填充数组列表?
- 填充数组(写入位置0x00000000的访问冲突)
- 从文件中读取输入并填充数组以存储数据供以后使用
- c++当循环在填充数组时没有正确终止时,希望能帮助退出此循环
- 填充数组会导致数组周围的堆栈损坏
- Cuda有效地将数据插入到未排序的填充数组中
- 填充数组的 C++ 函数
- 访问部分填充数组上的第一个打开元素
- 将一个字节数组从C#传递到C++填充数组的C++com对象中
- 如何使用向量中的信息填充数组并从数组中选择随机项
- C,填充数组使用dec2bin转换器