读取文件所需的 std::getline 的替代方案
Alternative to std::getline needed for reading a file
考虑以下方法,该方法从文本文件中读取一行并对其进行标记:
std::pair<int, int> METISParser::getHeader() {
// handle header line
int n; // number of nodes
int m; // number of edges
std::string line = "";
assert (this->graphFile);
if (std::getline(this->graphFile, line)) {
std::vector<node> tokens = parseLine(line);
n = tokens[0];
m = tokens[1];
return std::make_pair(n, m);
} else {
ERROR("getline not successful");
}
}
std::getline
发生崩溃(pointer being freed was not allocated
- 此处不详细介绍)。如果我在其他系统上编译代码,则不会发生崩溃,并且很可能不是我自己的代码中的错误。目前我无法解决这个问题,也没有时间,所以我会在你的帮助下尝试绕过它:
你能建议一个不使用std::getline
的替代实现吗?
编辑:我在Mac OS X 10.8与gcc-4.7.2上。我尝试使用gcc-4.7在SuSE Linux 12.2上,崩溃没有发生。
编辑:一种猜测是parseLine
损坏了字符串。以下是完整性的代码:
static std::vector<node> parseLine(std::string line) {
std::stringstream stream(line);
std::string token;
char delim = ' ';
std::vector<node> adjacencies;
// split string and push adjacent nodes
while (std::getline(stream, token, delim)) {
node v = atoi(token.c_str());
adjacencies.push_back(v);
}
return adjacencies;
}
您可以随时编写自己的更慢更简单的getline
,只是为了使其工作:
istream &diy_getline(istream &is, std::string &s, char delim = 'n')
{
s.clear();
int ch;
while((ch = is.get()) != EOF && ch != delim)
s.push_back(ch);
return is;
]
相关文章:
- 运行同一解决方案的另一个项目的项目
- Seg Fault Issue C++ (file IO / getline)
- Project Euler问题4的错误解决方案
- 计算每个节点的树高,帮助我解释这个代码解决方案
- 当用户键入分隔符时,停止getline()输入
- C++:Application.cpp中抛出了未解析的外部符号(解决方案在问题的末尾,供未来的读者参考)
- visual c++,如何获取解决方案目录中的代码
- getline() 的原型/库是什么;
- 错误 没有与参数列表匹配的重载函数"getline"实例
- 有没有办法在远程设备上打开和编辑visual Studio 2017解决方案
- C++Matching Brackets 2解决方案不起作用
- 在 ubuntu3 上C++ goto 定义有什么解决方案吗16.04?
- 如何在 c++ 中使用 ',' 作为 getline 分隔符
- 错误:调用'getline'没有匹配函数
- C++11 中不同类型的对象的 std::array 的替代方案
- 如何在 c++ 中使用 getline 从文件中读取字符串?
- 在 leetcode 上提交解决方案时出现堆栈缓冲区溢出错误
- 别名模板的专业化 C++11 中没有开销的最佳替代方案
- C++ getline(cin,变量)行为不端.网站上没有任何解决方案有帮助
- 读取文件所需的 std::getline 的替代方案