Is there any way to skip comments in text file by putting a // or something I'm pretty sure fortran has something similar and you use a # in the text file.
#include <iostream>
#include <string>
#include <sstream>
std::istream& get_line_strip_comments( std::istream& stm, std::string& str )
{
if( std::getline( stm, str ) )
{
auto pos = str.find( "//" ) ;
if( pos == 0 ) return get_line_strip_comments( stm, str ) ;
elseif( pos != std::string::npos ) str.erase(pos) ;
}
return stm ;
}
int main()
{
std::istringstream stm( R"(
this is a line with no comments
// this is a comment line
some text // and then a comment
more text / / this is not a comment // but this is\n)" ) ;
std::string str ;
while( get_line_strip_comments( stm, str ) ) std::cout << str << '\n' ;
}
i'd be surprised if any language natively does this.
assuming you're reading your lines into a std::string then something like this would 'ignore' them:
1 2 3 4 5 6 7 8 9 10 11 12
std::string lineInput;
// read the line and stick contents in lineInput
if( ! (lineInput[0]=='/' && lineInput[1]=='/') )
{
// do your stuff in here
}
else
{
// line is 'ignored'
}
Yes there is a way, I have no idea why mutexe said there wasn't...
Here is a very minor example. Just check if the first character of the line in the file is a #, if it is skip that line. This is only a minor example and needs more work but I didn't want to do it all for you ;p. Specifically you need to take care of any white spaces that come in front of things.
In this example I used '#' for the character but you can easily modify it to look for // instead by using if (line[0] == '/' && line[1] == '/') continue; other other methods of doing this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main()
{
fstream file("myfile.txy");
string line;
while (getline(file, line))
{
// Skips the line if the first character is a '#'. If there is spaces or whitespace before it it wont skip it
// So you might want to consider making something that trims the whitespaces infront of everything.
if (line[0] == '#') continue;
// You other stuff goes here
}
}