【问题标题】:C++ How to read the specific element from a text file into a array?C ++如何将文本文件中的特定元素读入数组?
【发布时间】:2012-11-28 13:20:16
【问题描述】:

我想做的是,现在我知道数字“10”的索引,我想将它读入ary。

#include <iostream>
#include <fstream>
using namespace std;

int ary[1];
ifstream inData;
inData.open("num.txt");
for (int i=1;i<2;i++){
    inData >> ary[0];
}

num.txt: 0   10   20
three number and separate by a '\t'

但这不起作用,我该怎么办?

【问题讨论】:

    标签: c++ arrays file stream


    【解决方案1】:

    它是您要查找的第二个数字,因此请将 i 更改为 0 或将 int ary[2] 或只使用 int ary,因为您知道索引,并且之前在前一次迭代中写入的内容将被循环的每次后续迭代覆盖。

    int main() {
        int ary;
        ifstream inData;
        inData.open("num.txt");
        for (int i=0;i<2;i++){
            inData >> ary;
    
        }
        printf("%d\n",ary);
        return 0;
    }
    

    用数组

    int main() {
        int ary[2];
        ifstream inData;
        inData.open("num.txt");
        for (int i=0;i<2;i++){
            inData >> ary[i];
            printf("%d\n",ary[i]);  
        }
    
        return 0;
    }
    

    【讨论】:

    • 这行得通!没有数组的那个是我真正想要的。但是,num.txt 有大约 90 亿个元素,我必须多次针对 num.txt 中的不同索引元素执行此搜索操作。有没有更快的方法来做到这一点?也许使用指针来定位特定元素?
    • 你可以使用诸如 fread() 之类的东西一次将它的块读入内存,就像一个数组一样,直到你到达适当的块,然后计算给定块中的索引通过做 index%chunk_size 这应该工作。否则,您将不得不将整个文件迭代到您的索引。这还涉及使用 FILE 指针而不是 ifstream。
    【解决方案2】:

    您的 int 数组的大小为 1。我认为它无法遍历文件。

    保留更多空间以便能够读取 3 个值,例如,

    int ary[3];
    

    并将您的循环更改为:

    for (int i=0;i<3;i++)
    

    我认为你也应该添加这个:

    for (int i=0;i<3;i++)
    inData.read(buffer,sizeof(int))
    

    【讨论】:

      【解决方案3】:

      您正在寻找一个特定的元素;那么就不需要数组了。

      #include <iostream>
      #include <fstream>
      
      using namespace std;
      
      int main()
      {
          int elementValue = 0;
          int indexOfElement = 2;
          ifstream inData;
          inData.open("num.txt");
          if (!inData.good())
          {
              std::cout << "Cannot open file" << std::endl;
              return 1;
          }
          int currentElement = 1;
          while(currentElement <= indexOfElement && inData.good())
          {
              inData >> elementValue;
              ++currentElement;
          }
          if (inData.good())
              std::cout << "Found: " << elementValue << std::endl;
          else 
              std::cout << "Failed to find enough elements" << std::endl;
      
          return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 2020-05-22
        • 2020-01-20
        • 2010-09-29
        • 1970-01-01
        • 1970-01-01
        • 2010-12-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多