Practice

Remove Comments from Source File

2024/May/June·Variant 1·Q8(a/b)
HARDFile Handling

Adapted from Cambridge International AS & A Level Computer Science (9618), May/June 2024 Paper 21, Question 8.

Write:

  • function DeleteComment(Line) to return Line after removing any comment. Comments start with //.
  • function Stage_1(StudentName) to read StudentName & "_src.txt", remove comments from each line, skip blank lines, write the remaining lines to StudentName & "_S1.txt", and return the number of lines written.

The test harness creates the source file from the input, calls Stage_1(), outputs the returned count, then outputs the cleaned file.

Input: Student name, number of source lines, then each source line. Output: Count of written lines, then each line written to the stage 1 file.

Example:

Input:  Ali
        4
        OUTPUT "Hello"// greeting
        // skip
        DECLARE X : INTEGER
        X <- 1
Output: 3
        OUTPUT "Hello"
        DECLARE X : INTEGER
        X <- 1
Premium is coming soon. All grading features are currently unlocked.

Sample Test Cases

Test 1: Inline and full-line comments
Inputs: Ali, 4, OUTPUT "Hello"// greeting, // skip, DECLARE X : INTEGER, X <- 1
Expected: 3 OUTPUT "Hello" DECLARE X : INTEGER X <- 1
Test 2: All lines removed
Inputs: Sam, 3, // comment only, // another comment, // final
Expected: 0