所以我在这个网站上看到很多解决方案和关于从C++文本文件读入的教程,但还没有找到解决我的问题的方法。我是C++的新手,所以我觉得我无法将一些文档拼凑在一起来理解这一切。C++从文本文件中读取数字,忽略注释
我想要做的是读取文本文件数字,而忽略文件中用“#”表示的注释。因此,一个例子文件将是这样的:当没有任何意见
#here is my comment
20 30 40 50
#this is my last comment
60 70 80 90
我的代码可以阅读精细的数字,但我不明白解析流不够好,忽略注释。它现在是一种黑客解决方案。
/////////////////////// 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 /////////////////
有没有一种方法,我可以将意见用此溶液处理或者我需要一种不同的方法?任何建议将是伟大的,谢谢。
'line.assign(line.substr(0,line.find('#')));'(作为while循环中的第一条语句)将会是快速做出必要改变的一种方法。 – jogojapan
这非常非常简单。你说你不明白上面的代码足以修改它。我想在你尝试别的之前,你需要花一些时间去理解。 – john
你有没有试过它与文件中存在的评论?正如所写的,代码将忽略第一部分之后的行的任何部分,该部分不是包含注释的有效数字。 –