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

How do I put the values from an external file into an array?

本文关键字:数组 外部 文件      更新时间:2023-10-16

我正在尝试读取一个外部文件,并将文件中的所有字符串放入字符串类型的数组中。

这是我的主要功能:

#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;
}

你可能是指

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

此外,请考虑使用std::vector而不是数组。此外,变量"word"未使用。要打印内容,请使用

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