从c转换为c++时的归档错误

Filing mistake when converting from c to c++

本文关键字:错误 c++ 转换      更新时间:2023-10-16

我遇到的问题是,我用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);

如果您想继续使用char数组和c字符串,请使用istream::getline()读取您的c程序:

infile.open("small.txt");
while(infile.getline(word, MAX_LINE) )
{
    temp = root;
    buildTrie(temp, word);
}
infile.close();

小心循环读取操作。

现在,根据代码的其余部分,您还可以考虑从char[]迁移到string。这有很多优点,而且更多地体现在c++哲学中。然后,您可以按照Jerry在回答中的建议使用std::getline()