如何将外部文件中的值放入数组中?

问题描述:

我想读取一个外部文件,并将文件中的所有字符串放入字符串类型的数组中。如何将外部文件中的值放入数组中?

这是我的主要功能:

#include <iostream> 
#include "ReadWords.h" 
#include "Writer.h" 
#include <cctype> 
#include <string> 

using namespace std; 

int main() { 

    int count; 
    const int size = 10; 
    string word_search[size]; 
    string word; 

    cout << "Please enter a filename: " << flush; 
    char filename[30]; 
    cin >> filename; 

    ReadWords reader(filename); 
    while (reader.isNextWord()){ 
     count = count + 1; 
     reader.getNextWord(); 

    } 

    cout << "Please enter the name of the file with the search words: " << flush; 

    char filename1[30]; 
    cin >> filename1; 

    ReadWords reader1(filename1); 
    while (reader1.isNextWord()) { 

这就是我想要的字符串存储在名为word_search一个数组,然而,这不是目前的工作。如何将字符串存储在数组中?

 for(int i = 0; i < size; i++){ 
      word_search[i] = word; 

     } 
    } 

这是我在哪里打印数组的内容,看看我是否成功。

cout << word_search << endl; 



    return 0; 
} 

这是所有方法中有一个名为ReadWords.cpp一个单独的文件被宣布:

#include "ReadWords.h" 
#include <cstring> 
#include <iostream> 
using namespace std; 

void ReadWords::close(){ 
    wordfile.close(); 

} 

ReadWords::ReadWords(const char *filename) { 
    //storing user input to use as the filename 

     //string filename; 

     wordfile.open(filename); 

     if (!wordfile) { 
      cout << "could not open " << filename << endl; 
      exit(1); 
     } 
} 

string ReadWords::getNextWord() { 

    string n; 


    if(isNextWord()){ 
     wordfile >> n; 
     //cout << n << endl; 

     int len = n.length(); 
     for(int i = 0; i < len ; i++) { 

      if (ispunct(n[i])) 
        { 
         n.erase(i--, 1); 
         len = n.length(); 
        } 
     } 
      cout << n << endl; 
     return n; 

    } 
} 

bool ReadWords::isNextWord() { 

     if (wordfile.eof()) { 
      return false; 
     } 
     return true; 
} 
+0

问题是什么?如果设置正确,for循环可以很好地工作。 –

+0

我的第一个猜测告诉我你要替换'word_search [i] = word; '''''word_search.push_back(word);' –

+0

@CaptainGiraffe:啊,是那个着名的函数'((std :: string)[10]):: push_back'。 –

你可能是指

size_t count = 0; 
    while (reader.isNextWord()){ 
     word_search[count] = reader.getNextWord(); 
     ++count; 
    } 

而且,考虑使用的std ::矢量而不是一个数组。另外,变量“单词”未被使用。 要打印内容使用

for (size_t i = 0; i < size; ++i) 
     cout << word_search[i] << endl;