简体   繁体   中英

Need to store a text file of words into a char array in c++

So suppose you have aa text file, and it contains 10 random words. My instructions are to get those words and store it into a char array. I know you can do this with something like 'char example[2][10] = {'word1', 'word2'}, but thats only if you know the words in particular. How could I apply this in a loop to add all the words? We can assume that we know how many words there are, and word lengths. I am using fstream to read from the file.

To do this, you must keep the number of words read so far. The index starts at 0

std::ifstream f("/path/to/file.txt");
int i = 0;
char words[10][20];
std::string word;
// read the words in a loop
while (f >> word) {
    // copy the word to char array
    word.copy(words[i], sizeof(words[i]);
    ++i;
}

Although, in C++ you'd rather use std::vector and push_back or emplace_back

std::ifstream f("/path/to/file.txt");
std::vector<std::string> words;
std::string word;
// read the words in a loop
while (f >> word) {
    // append the word to vector
    words.push_back(word);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM