c++ - 从 c 转换为 c++ 时出现归档错误

标签 c++ c file-handling

我遇到的问题是,我用 c 编写了一段代码来归档我的程序,当我用 c++ 编写相同的代码时,它不起作用。请帮我找出我在用 C++ 编写代码时犯的错误。

C 代码:

FILE* dict = fopen("small.txt", "r");
char word[MAX_LINE];
Node* root = newNode(); // pointer to main root of Trie
Node* temp;
while (fgets(word, MAX_LINE, dict) != NULL) {
      temp = root;
    buildTrie(temp, word);
}
fclose(dict);

C++ 代码:

ifstream infile;
char word[MAX_LINE];
Node* root = newNode(); // pointer to main root of Trie
Node* temp;

infile.open("small.txt");
while(infile)
{
  for(int i =0;i<MAX_LINE;i++)
  {
      infile>>word[i];
      temp = root;
    buildTrie(temp, word);

  }
}
infile.close();

最佳答案

如果我用 C++ 编写这样的代码,我可能会编写更像这样的代码:

std::string word;

while (std::getline(infile, word))
    buildTrie(temp, word);

老实说,我怀疑我是否会编写完全一样的代码 - 我可能会将 trie 包装到一个类中,因此代码看起来更像是:

Trie t;
std::string word;

while std::getline(infile, word))
    t.add(word);

关于c++ - 从 c 转换为 c++ 时出现归档错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34188057/

相关文章:

c++ - "const"在 C 和 C++ 中有何不同?

c++ - 为什么抓取窗口标题的代码会导致应用程序崩溃?

c - 在 C 中仅使用 While 和 do while 循环求 5 个数字和 N 个数字的平均值

c - RPI 通过 PWM 驱动伺服(接线/C 编程)

java - 如何在spring boot项目启动时创建目录

c++ - 尝试通过多个函数移动数组并遇到一个我不知道如何修复的错误

C++ 类继承和赋值运算符

c - INSERT INTO 语句中的语法错误

c - fscanf 无法从 txt 文件读取数据

c - 如何列出 C 目录中目录中的文件?