【问题标题】:Reading arrays from file c++从文件 c++ 中读取数组
【发布时间】:2016-11-04 00:49:40
【问题描述】:

我正在尝试制作一个到目前为止只需要读取文件并将其内容保存在数组中的程序。 cout 是一个测试,看看单词是否会保存到数组中,但它没有用。执行时,它所做的只是打印到屏幕空白处,最后打印文件名。

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <iostream>
#include <fstream>
#include <streambuf>
#include <ctime>
#include <time.h>
#define MAX 10000

void readFile(fstream& wordFile, string words[], int &wordarrayLength)
{
     string word;
     int i=0;

       while(i < MAX)
       {
           getline(wordFile,word);
           words[i] = word;
           i++;
           cout << words[i] << endl;
       }

     wordarrayLength = i;

     wordFile.close();
}

int main()
{

  string words[MAX];
  int arraylength;
  fstream file ("words.txt", ios::in);

  readFile(file,words,arraylength);

}

【问题讨论】:

  • 注意:你把每一行文本保存到words[i],你递增i,然后打印words[i]的内容。继续重读上一句,直到找出错误为止。
  • 为什么不用矢量
  • @SamVarshavchik 将控制台行的输出编辑为cout &lt;&lt; word &lt;&lt; endl;,结果是一样的,我认为这是我传递文件参数的方式,但看起来很好。
  • fstream 的传递方式没有问题。
  • @SamVarshavchik 我明白你的意思。代码将字符串存储在words[i] 中,但cout 是数组中尚未定义的下一个字符串......但是如果我更改它cout &lt;&lt; word &lt;&lt; endl; 输出应该是从文件中提取的数组,它不是,

标签: c++ arrays string parameters ifstream


【解决方案1】:

我错过了编译器正在寻找的文件。此代码运行良好。

【讨论】:

    【解决方案2】:

    试试这样的:

    //since you are updating the array pass it in by reference as well.
    void readFile(fstream& wordFile, string &words[], int &wordarrayLength)
    {
         int i=0;
    
           while(i < MAX)
           {
               //each item in the array has to be it's own string
               //the previous code simply reused the same string each time
    
               string word;
               getline(wordFile, word);
               words[i] = word;
               cout << words[i] << endl;
               i++;
           }
    
         wordarrayLength = i;
    
         wordFile.close();
    }
    

    很遗憾,我没有你的文件或编译器,所以我无法调试它。

    【讨论】:

      猜你喜欢
      • 2014-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-05
      • 2021-10-19
      • 1970-01-01
      • 2017-08-15
      相关资源
      最近更新 更多