首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++将双精度值从同时包含字符串和双精度值的文件读取到二维数组中

问C++将双精度值从同时包含字符串和双精度值的文件读取到二维数组中
EN

Stack Overflow用户
提问于 2016-02-28 06:22:10
回答 2查看 1.4K关注 0票数 2

我正在开发一个程序,其中有一个包含州名称的输入文件,每个州有三种不同的税:销售税、财产税和所得税。我正在尝试将税值(读取为双精度变量)读取到双精度类型的数组中。下面是我的代码:

代码语言:javascript
复制
#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;
}

以下是数据文件:

代码语言:javascript
复制
    TEXAS        .0825 .02  -.03
    CALIFORNIA   .065  .04   .05
    MARYLAND     .03   .025  .03
    MAINE        .095  .055  .045
    OHIO         .02   .015  .02

从this开始,程序输出数组,除了每个位置都读取-9.25596e+061。我想知道这是不是因为程序试图将字符串读入数组。我还想知道是否有一种方法可以逐行忽略文件中的字符串,以便只将双精度值读入数组。

EN

回答 2

Stack Overflow用户

发布于 2016-02-28 06:32:52

在for循环中读取整行代码。您不需要稍后再执行fin >> array[i][j]。相反,你应该这样做:

代码语言:javascript
复制
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
    }
}
票数 0
EN

Stack Overflow用户

发布于 2016-02-28 06:40:12

这应该可以完成这项工作:

代码语言:javascript
复制
#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行,则需要重写代码。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35676197

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档