c++根据数据类型将输入文件中的数据读入3个并行数组

标签 c++ arrays input fstream parallel-arrays

无法将输入文件中的数据排序到指定的数组中。输入文件包含字符串、 double 和整数。

  • TN 54.5 7
  • 肯塔基州 65.6 23
  • PA 123.3 30
  • 等等

共有14行string、double、int数据类型。数据将以与文件相同的格式打印到屏幕上。我已经能够使用一个“字符串数组”将数据打印到屏幕上,但是数据没有按照上面指定的顺序打印。我试过使用 getline() 并且通过研究看到很多人谈论简单地使用“输入>>变量[max];”对于每个单独的变量。这只会打印一个巨大的数字,而输入文件中不包含其中的 53 个数字。我觉得我让这件事比现在更难了。我知道我的阵列太小,无法读取所需的数据量(我计划修复)。不要求有人为我解决这个问题。只需要指出正确的方向。有没有更简单的方法将数据排序到所需的数组?

下面的代码是我用一个数组读取所有数据类型的代码。

#include <iostream>
#include <fstream>

using namespace std;

void readData(ifstream& input, string []);
int main()
{
   string data[14];
   char filename[256];
   fstream input;

   cout << "Enter file name: ";
   cint >> filename;

   input.open(filename);
   if (input.fail())
   {                                  
      cout << "opening file fail." << endl;
   }

   readData(input, data);

   input.close();
   return(0);
}             

void readData(ifstream& input, string data[14])
{
    int count;

    count = 0;
    while (count < 14 && !input.eof())
    {
       input >> data[count];
       count << data[count] << endl;
       count++;
    }
}                

最佳答案

为什么不是单循环? (参见live here)

#include <iostream>
#include <sstream>
#include <vector>

void read_data(std::istream& input, std::vector<std::string>& strings, std::vector<double>& doubles, std::vector<int>& ints) {
  std::string s; double d; int i;
  while( input >> s >> d >> i ) {
    strings.push_back(s);
    doubles.push_back(d);
    ints.push_back(i);
  }
}

int main() {
  std::istringstream i { "FN 3.2 22\nBB 3.48 48\nXX 2.03 172\n" };
  std::vector<std::string> strings;
  std::vector<double> doubles;
  std::vector<int> ints;

  read_data(i, strings, doubles, ints);
  std::cout << "strings:\n";
  for(auto s: strings) std::cout << "  " << s << "\n";
  std::cout << "doubles:\n";
  for(auto d: doubles) std::cout << "  " << d << "\n";
  std::cout << "ints:\n";
  for(auto i: ints) std::cout << "  " << i << "\n";
}

关于c++根据数据类型将输入文件中的数据读入3个并行数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22975348/

相关文章:

javascript - 带有嵌套数组的微模板

c - 在 C 中,如何在不使用 ENTER 的情况下获取输入(整数)?

c# - 如何读取单个键盘字符(如 getch)?

java - Java 如何计算文件的哈希值?

javascript - 输入位置在 Iphone 上无法正确显示

c++ - C/C++中是否有称为 "hypochecking"的术语?

c++ - 有没有办法为类中的所有成员选择使用 `std::optional`

python - 使用 Cython 包装返回 MPI 通信器的 C++ 函数

c++ - #include<utility> 在 dev c++ 头文件中

javascript - 将参数转换为数组