I would like to ignore empty line and line started with #

std::string line;  

while (getline(input,line))
{
  if (line[0] == '#') continue;

  if (line[0] == '?') continue;
  
...
}

Where ? is, I would like to put the end line character, but what is it in C++?

Dani AI

Generated

asked what the "end line" character is; correctly named it as '\n'. A key point that none of the original snippets emphasize clearly: std::getline removes the newline delimiter, so the string you get back will normally not contain '\n' at the end. That makes checking the returned string for '\n' unnecessary. Also avoid using line[0] without first checking line.empty() — that causes undefined behavior on empty lines. 's idea of grouping characters is a good direction, but comparing against "\n" in that set will never match because getline already stripped it.

A robust, practical approach is: strip a possible carriage return (from CRLF files), skip leading whitespace, then test the first non-space character for '#' (or treat the whole line as blank). The example below shows a safe pattern that handles these cases and avoids UB. It also demonstrates casting to unsigned char when calling std::isspace (important for portability).

auto is_blank_or_comment = [](const std::string& s) -> bool {
    if (s.empty()) return true;
    size_t i = 0;
    while (i < s.size() && std::isspace(static_cast<unsigned char>(s[i]))) ++i;
    return (i == s.size()) || (s[i] == '#'); // blank or starts with '#'
};

std::string line;
while (std::getline(input, line)) {
    if (!line.empty() && line.back() == '\r') line.pop_back(); // handle CRLF
    if (is_blank_or_comment(line)) continue;
    // process non-empty, non-comment line
}

Notes: use this when you want to ignore lines that are empty or that begin with # possibly after spaces. If comments can appear inline (after code), strip from the first # onward instead. For more advanced trimming or locale-aware parsing, consider a small helper trim function or a parsing library.

Recommended Answers

All 2 Replies

\n

You should do something like this :

const string& stringToAvoid = "#\n"; 
string line;
while(getline(cin,line)){
  if(stringToAvoid.find(line[0]) != string::npos) continue;
}

that way you can just add more character to stringToAvoid instead more if's

commented: Nice +9
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.