Nin*_*nda 1 c++ parsing inputstream
因此,我在这个网站上看到了很多解决方案以及有关从 C++ 文本文件中读取内容的教程,但尚未找到解决我的问题的方法。我是 C++ 新手,所以我认为我在拼凑一些文档以理解这一切方面遇到了困难。
我想做的是读取文本文件编号,同时忽略文件中用“#”表示的注释。因此,示例文件如下所示:
#here is my comment
20 30 40 50
#this is my last comment
60 70 80 90
Run Code Online (Sandbox Code Playgroud)
当没有任何注释时,我的代码可以很好地读取数字,但我不明白如何很好地解析流以忽略注释。现在它是一种黑客解决方案。
/////////////////////// Read the file ///////////////////////
std::string line;
if (input_file.is_open())
{
//While we can still read the file
while (std::getline(input_file, line))
{
std::istringstream iss(line);
float num; // The number in the line
//while the iss is a number
while ((iss >> num))
{
//look at the number
}
}
}
else
{
std::cout << "Unable to open file";
}
/////////////////////// done reading file /////////////////
Run Code Online (Sandbox Code Playgroud)
有没有办法可以将评论处理与此解决方案结合起来,或者我是否需要不同的方法?任何建议都会很好,谢谢。
如果您的文件#始终包含在第一列中,则只需测试该行是否以#如下形式开头:
while (std::getline(input_file, line))
{
if (line[0] != "#" )
{
std::istringstream iss(line);
float num; // The number in the line
//while the iss is a number
while ((iss >> num))
{
//look at the number
}
}
}
Run Code Online (Sandbox Code Playgroud)
明智的做法是修剪前导和尾随空格的行,例如此处所示:Remove Spaces from std::string in C++
| 归档时间: |
|
| 查看次数: |
17317 次 |
| 最近记录: |