My program does compile and counts the number of lines of code, which is LOC: 20. My issue this, according to my code instruction it should not count comments (//) and also shouldn't count blank lines of code. Unfortunately my code is counting // and white space.
What seems to be working is #, all three includes are not being counted. That’s a good sign, ha-ha. Any suggestions on how to fix this code. I’m using the same technique not to count #. Why isn't working for comments and blank lines? I’m pretty sure that my logic is correct. I think my problem is maybe syntax.
" if (s[0] == "//") " would always return false. You're comparing the first character of the line to 2 characters. To check if the 2 initial characters are "//", use " if (s.substr(0, 2) == "//") ".
As for the blank line, the first character in it wouldn't be a "" either. The first character in a blank line is actually a "\n" (a new line character).
I modified my program to read from another file named example.cpp
My modified code is this:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string line;
ifstream myfile ("example.cpp");
int count = 0;
const int A = 3;
int s[A];
if (myfile.is_open())
{
while ( getline (myfile,line) ){
count++;
if (s[0] == '/' || s[0] == ' ' || s[0] == '#'){
count--;
}
cout << "This is your LOC: " << line << endl;
}
myfile.close();
}
//else cout << "unable to open file";
return 0;
}
The program should read the number of lines of code omitting comments and blank lines.
My program should read the logical line from this program that looks like this:
OK, I'm making some progress. My program does compile and output the number of line per code, but it shouldn't count comments and blank lines. I tried using (s.substr(0,2) == "//") as suggested but it didn't work. I definitely appreciate any recommendations and suggestions. Thanks guys.
This is my improved code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int A = 3;
int main()
{
string s;
ifstream myfile ("example.cpp");
int count = 0;
//int A = 3;
getline(myfile, s);
if (myfile.is_open())
{
while ( getline (myfile, s) ){
count++;
if (s[0] == '/' || s[0] == ' ' || s[0] == '#'){
count--;
}
}
}
cout << "This is your LOC: " << count << endl;
return 0;
}