-1

I'm having some trouble with detecting two '//' as a char and then deleting from the first '/' till the end of the line (im guessing /n comes into use here).

{
    ifstream infile;

    char comment = '//';

    infile.open("test3.cpp");

    if (!infile)
    {
        cout << "Can't open input file\n";
        exit(1);
    }

    char line;
    while (!infile.eof())
    {
        infile.get(line);

        if (line == comment)
        {

            cout << "found it" << endl;
        }



    }

    return 0;
}

In the test3.cpp file there are three comments, so 3 lots of '//'. But I can't detect the double slash and can only detect a single / which will affect other parts of the c++ file as I only want to delete from the beginning of a comment to the end of the line?

Keir
  • 1
  • 2
  • Slash '/' is a single char. Double slash therefore is a string. – RvdK Oct 19 '14 at 11:44
  • `'//'` is not a single char, it will have an implementation-defined multi-character `int` value (which you then truncate back to a `char` so it's relatively worthless). – user657267 Oct 19 '14 at 11:45
  • But, the infile is reading through each character, and changing this will cause problems right? – Keir Oct 19 '14 at 11:46
  • Possible duplicate of [Why is iostream::eof inside a loop condition considered wrong?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – πάντα ῥεῖ Oct 19 '14 at 12:04

1 Answers1

0

I'm having some trouble with detecting two '//' as a char

That's because // is not a character. It is a sequence of two characters. A sequence of characters is known as a string. You can make string literals with double quotation marks: "//".

A simple solution is to compare the current input character from the stream to the first character of the string "//" which is '/'. If it matches, then compare the next character from the stream with the second character in the string that is searched for. If you find two '/' in a row, you have your match. Or you could be smart and read the entire line into a std::string and use the member functions to find it.

Also:

while (!infile.eof())
{
    infile.get(line);
    // using line without testing eof- and badbit

This piece of code is wrong. You test for eofbit before reading the stream and process the input.

And your choice of name for the line variable is a bit confusing since it doesn't contain the entire. line but just one character.

eerorika
  • 181,943
  • 10
  • 144
  • 256
  • `char letter; while (!infile.eof()) { infile.get(letter); if (letter == '/' && firstDash == false) { firstDash = true; if(firstDash == true && letter == '/') { firstDash = false; cout << "comment found" << endl; //comment is found } firstDash = false; } }` I tried setting to something like this with boolean values but it would still print out 6 times. Also line is now letter. – Keir Oct 19 '14 at 14:31