从c转换为c++时的归档错误
Filing mistake when converting from c to c++
我遇到的问题是,我用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()
。
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 在某些循环内使用vector.push_back时出现分段错误
- MSVC多行宏编译器错误
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 错误:未在此范围内声明'reverse'