我正在执行一个程序,其中我有一个包含州名称的输入文件,以及每个州的三种单独税种:销售税、属性(property)税和所得税。我正在尝试将税值(读取为 double 变量)读入 double 类型的数组。这是我的代码:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
double a = 0,
b = 0,
c = 0;
double array[5][3];
string state_name;
ifstream fin;
fin.open("test.dat");
for (; fin >> state_name >> a >> b >> c;)
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 3; j++)
{
fin >> array[i][j];
cout << array[i][j] << "\t";
}
cout << endl;
}
}
return 0;
}
这是数据文件:
TEXAS .0825 .02 -.03
CALIFORNIA .065 .04 .05
MARYLAND .03 .025 .03
MAINE .095 .055 .045
OHIO .02 .015 .02
由此,程序输出数组,除了每个位置读取 -9.25596e+061。我想知道这是否是因为程序试图将字符串读入数组。我还想知道是否有一种方法可以逐行忽略文件中的字符串,以便只将 double 值读入数组。
最佳答案
您在 for
循环中读入整行。您以后不需要执行 fin >> array[i][j]
。相反,您应该这样做:
for (int i = 0; i < 5; i++)
{
fin >> state_name;
for(int j = 0; j < 3; ++j)
{
fin >> array[i][j];
cout << array[i][j] << '\t';
}
cout << endl;
if(!fin)
{
// handle an error reading the file
}
}
关于C++ 从包含字符串和 double 的文件中将 double 值读入二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35676197/