【问题标题】:Filing mistake when converting from c to c++从 c 转换为 c++ 时出现归档错误
【发布时间】:2015-12-09 20:08:32
【问题描述】:

我遇到的问题是我用 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++ 代码,它不会正确地创建一个 trie 结构,而对于 C 代码来说它工作得非常好。

标签: c++ c file-handling


【解决方案1】:

如果我在 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);

【讨论】:

  • 它的字符数组不是字符串。现在呢?
  • word.c_str() 可以帮助你。如果还没有,您必须调整 buildTrie 以获取 const char *
  • @user4581301:不。调整(或超载)buildTrie 以获取std::string const &amp;
【解决方案2】:

如果您想继续使用 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()

【讨论】:

  • 查看您的 C 代码,您显示的部分应该可以正常工作。一个简单的验证是显示单词而不是调用 buildTree():显示应该是相同的。我认为问题出在 buildTrie 中(如果您保留了一些 malloc() ,甚至是 newNode() )。您必须发布更多代码才能获得更多帮助。
猜你喜欢
  • 2016-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-30
  • 2013-03-06
  • 2019-05-01
相关资源
最近更新 更多