gpt4 book ai didi

c++ - 将文件中的每个单词读入 C++ 中的 char 数组

转载 作者:行者123 更新时间:2023-11-28 02:27:12 24 4
gpt4 key购买 nike

使用 ifstream() 读取文件然后将每个单词存储在 char 数组中的正确方法是什么?该字符数组最终将用于将当前单词输入到哈希表中。

我的代码:

int main()
{
int array_size = 4096;
char * filecontents = new char[array_size];
char * word = new char[16];
int position = 0;
ifstream fin("Dict.txt");

if(fin.is_open())
{

cout << "File Opened successfully" << endl;
while(!fin.eof() && position < array_size)
{
fin.get(filecontents[position]);
position++;
}
filecontents[position-1] = '\0';

for(int i = 0; filecontents[i] != '\0'; i++)
{
word[i] = filecontents[i];
//insert into hash table
word[i] = ' ';

}
cout << endl;
}
else
{
cout << "File could not be opened." << endl;
}
system("pause");
return 0;
}

最佳答案

除非万不得已,否则不要使用字符数组。将它们读入字符串,然后将字符串放入哈希表中。如果你没有哈希表,我可以推荐std::set吗? ?可能正好符合您的需要。

阅读资料。试一试:

int main()
{
ifstream fin("Dict.txt");
set<string> dict; // using set as a hashtable place holder.

if (fin.is_open())
{
cout << "File Opened successfully" << endl;
string word;
while (getline(fin, word, '\0'))
{ /* getline normally gets lines until the file can't be read,
but you can swap looking for EOL with pretty much anything
else. Null in this case because OP was looking for null */
//insert into hash table
dict.insert(word); //putting word into set
}
cout << endl;
}
else
{
cout << "File could not be opened." << endl;
}
system("pause"); // recommend something like cin >> some_junk_variable
return 0;
}

关于c++ - 将文件中的每个单词读入 C++ 中的 char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30135403/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com