-
February 7th, 2015, 05:21 PM
#1
Program shoudn't count comments and blank lines
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:
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;
}
-
February 8th, 2015, 05:30 AM
#2
Re: Program shoudn't count comments and blank lines
A line starting with a space (or a tab) is not necessarily a blank line - it could be part of a line indentation. A comment line starting with // might also have some preceding spaces or tabs. .length() returns the number of chars in the string so if this 0 then the line is blank. To find the position of the first non-space/tab then .find_first_not_of() can be used. See http://www.cplusplus.com/reference/s..._first_not_of/ A possible way of doing this could be
Code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const string fnam = "example.cpp";
const char delim[] = { ' ', 9, 0 };
int main()
{
ifstream myfile(fnam.c_str());
if (!myfile.is_open()) {
cout << "Could not open file\n";
return 1;
}
int count = 0;
string s;
size_t pos;
while (getline(myfile, s))
if (s.length() && (pos = s.find_first_not_of(delim)) != string::npos)
count += !(s.substr(pos, 2) == "//" || s[pos] == '#');
cout << "This is your LOC: " << count << endl;
return 0;
}
All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!
C++23 Compiler: Microsoft VS2022 (17.6.5)
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|