Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
需要在C++中将文字文件存储到字符数组中_C++_Arrays_Multidimensional Array_Char - Fatal编程技术网

需要在C++中将文字文件存储到字符数组中

需要在C++中将文字文件存储到字符数组中,c++,arrays,multidimensional-array,char,C++,Arrays,Multidimensional Array,Char,假设你有一个文本文件,它包含10个随机单词。我的指令是获取这些单词并将其存储到char数组中。我知道你可以用类似“char-example[2][10]={'word1',word2'}这样的东西来实现这一点,但这只有在你特别了解单词的情况下才能实现。我如何在循环中应用这个来添加所有单词?我们可以假设我们知道有多少个单词,以及单词的长度。我正在使用fstream读取文件。要执行此操作,您必须保留到目前为止读取的字数。索引从0开始 虽然C++中你更喜欢使用和推回或置换-< /P> 我们可以假设我们

假设你有一个文本文件,它包含10个随机单词。我的指令是获取这些单词并将其存储到char数组中。我知道你可以用类似“char-example[2][10]={'word1',word2'}这样的东西来实现这一点,但这只有在你特别了解单词的情况下才能实现。我如何在循环中应用这个来添加所有单词?我们可以假设我们知道有多少个单词,以及单词的长度。我正在使用fstream读取文件。

要执行此操作,您必须保留到目前为止读取的字数。索引从0开始

虽然C++中你更喜欢使用和推回或置换-< /P>


我们可以假设我们知道有多少个单词,以及单词的长度,如果你知道的话,到底是什么问题?我怎样才能在这个字符数组中添加单词呢。举个例子,如果我给你一个封闭的盒子,告诉你有10个名字,名字长度不超过20个字母。我知道这些信息,但是当我从文件中读取这些名称时,如何将它们附加到char变量中呢?正如我在帖子中所说,我知道一旦我启动变量,我就可以添加完整的单词,但是一旦我已经启动了变量,我怎么做呢?for循环与std::ifstream::getline或std::ifstream::read组合,这取决于需求?
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;
}
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);
}