Remove comments like the preprocessor
Strip // and / / comments, leaving string literals untouched. A medium embedded C problem (The compilation pipeline), run and graded in the browser.
medium · The compilation pipeline · compilation · preprocessor · strings
Before compiling, the preprocessor replaces every comment with a space. Write strip_comments(src, out), which copies src to out with:
/* ... */comments replaced by one space,// ...comments removed up to (not including) the end of the line,- everything inside string literals (
"...", which may contain\") left exactly as it is, even if it looks like a comment.
Starter code
void strip_comments(const char *src, char *out) {
while (*src) {
if (src[0] == '/' && src[1] == '/') {
while (*src && *src != '\n') src++;
} else {
*out++ = *src++;
}
}
*out = 0;
}Example tests
Line comments
show("int x = 1; // the count\nint y;");Expected output:
[int x = 1;
int y;]Block comments
show("a = b /* old: c */ + d;");
show("x/**/y");Expected output:
[a = b + d;]
[x y]Learn it first
- The compilation pipeline · Preprocessor, compiler, assembler and linker, and what each one produces.