Programming contests

20 Programming Exercise for Beginners

January 1, 2019, 12:00 AM – December 31, 2019, 12:00 AM

Single Line Comment

Create a program that can remove the single-line comments from the input lines. A single-line comment is the part of the line which starts with two slash characters (“//”) and lasts till the end of the line.

Input Specification

The input is an ASCII text without any restrictions.

Sample Input

  1. apple
  2. orange
  3. // banana
  4. berry // mango
download as text file

Output Specification

The output contains the input lines without the single-line comments.

Output for Sample Input

  1. apple
  2. orange
  3. berry 
download as text file

Hints and Guide

If the length of the input lines are limited, then we can easily solve the exercise line by line. After reading an input line, for example with the help of the fgets function, we can use strstr to find the “//” substring. If the function returns -1, indicating that the string does not contain the slashes, then the full line, otherwise the beginning of the line up to the return value of the strstr function should be repeated on the standard output.

Because there is no limit to the line length, we suggest another solution. One boolean variable can be used to indicate whether the previous input character is part of a comment. Note that the C language does not have a dedicated boolean type, we can use integers instead. One single slash character does not necessarily indicate a starting comment, hence both the current and the previous characters must be stored. When a double slash occurs, we stop printing to the output, while the newline character turns the output on again. This status is stored in the boolean variable.

One possible solution is available in: main.c.

Possible Improvements

Processing the input character by character can be very slow. A character buffer and the use of the fgets function can make the solution faster.

Acknowledgement This work was supported by the construction EFOP-3.4.3-16-2016-00021. The project was supported by the European Union, co-financed by the European Social Fund.
University of Debrecen; Faculty of Informatics; v. 09/30/2024