[英]C++ Reading double values into a 2D array from a file containing both strings and doubles
我正在通過一個程序工作,在該程序中,我有一個包含州名的輸入文件,以及每個州的三種單獨的稅:營業稅,財產稅和所得稅。 我正在嘗試將稅額(讀為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
}
}
這應該做的工作:
#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行以上,則需要重寫代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.