我正在开发一个程序,其中有一个包含州名称的输入文件,每个州有三种不同的税:销售税、财产税和所得税。我正在尝试将税值(读取为双精度变量)读取到双精度类型的数组中。下面是我的代码:
#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从this开始,程序输出数组,除了每个位置都读取-9.25596e+061。我想知道这是不是因为程序试图将字符串读入数组。我还想知道是否有一种方法可以逐行忽略文件中的字符串,以便只将双精度值读入数组。
发布于 2016-02-28 06:32:52
在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
}
}发布于 2016-02-28 06:40:12
这应该可以完成这项工作:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
double array[5][3];
string state_name;
ifstream fin;
fin.open("test.dat");
// Read the file row by row
int row =0;
while(fin >> state_name >> array[row][0] >> array[row][1] >> array[row][2]) {
++row;
}
// Print the result
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 3; j++) {
cout << array[i][j] << "\t";
}
cout << endl;
}
return 0;
}如果您允许我进一步考虑,您可能更喜欢将每一行推入向量,而不是静态数组。否则,如果文件的行数超过5行,则需要重写代码。
https://stackoverflow.com/questions/35676197
复制相似问题