【问题标题】:Need to store a text file of words into a char array in c++需要将单词的文本文件存储到c ++中的char数组中
【发布时间】:2018-02-19 18:19:49
【问题描述】:

假设您有一个文本文件,其中包含 10 个随机单词。我的指示是获取这些单词并将其存储到 char 数组中。我知道你可以用'char example[2][10] = {'word1', 'word2'} 之类的东西来做到这一点,但前提是你特别知道这些词。我如何在循环中应用它来添加所有单词?我们可以假设我们知道有多少单词和单词长度。我正在使用 fstream 从文件中读取数据。

【问题讨论】:

  • "我们可以假设我们知道有多少单词和单词长度" 如果你知道这一点,那么问题出在哪里?
  • 我怎样才能将单词附加到这个 char 数组中。一个例子是,如果我给你一个封闭的盒子,告诉你有 10 个名字,名字的长度不超过 20 个字母。我知道这些信息,但是当我从文件中读取这些名称时,如何将它们附加到我的 char 变量中?就像我在帖子中所说的那样,我知道一旦启动变量就可以附加完整的单词,但是一旦我已经启动了变量,我该怎么做呢?
  • for 循环结合std::ifstream::getline(或std::ifstream::read,取决于要求)?

标签: c++ arrays multidimensional-array char


【解决方案1】:

为此,您必须保持目前已阅读的字数。索引从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;
}

尽管在 C++ 中,您更愿意使用 std::vectorpush_backemplace_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);
}

【讨论】:

    猜你喜欢
    • 2016-03-07
    • 2014-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-11
    • 2015-06-16
    • 1970-01-01
    相关资源
    最近更新 更多