Tilpas kommenteret kode
Hej eksperterJeg leger lidt med, hvordan en kode skal stilles op mht informationer, kommentarer osv.
Sådan ud fra hvad jeg selv synes virker rimeligt er jeg kommet frem til følgende.
/*
- Filename: main.cpp
- Made by: Thomas N. Jensen
- Last modified: 30/3 - 2006
- Description: This program is the solution to the challenge at http://www.cprogramming.com/challenges/count.html The purpose of the program is to take the name of a file as an argument and if it is a valid filename print out the number of lines in the file.
- Known bugs: None
*/
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char *argv[])
{
// Check if there is given the right number of arguments.
// If not the program will tell if there is to few or to many, print how to correctly use the program
// and quit with 1
if(argc!=2)
{
if(argc<2)
{
cerr<<"To few arguments! "; // The line will be completed further down
}
else if(argc>2)
{
cerr<<"To many arguments! "; // The line will be completed further down
}
cerr<<"Use the program like this: fileCount file.type"<<endl;
return 1;
}
ifstream inFile(argv[1]); // Input file
int lineCount=0;
char buff[255]; // Stores the line which is being counted
if(inFile.fail()) // Check if something is wrong with the file. Fx if it exists.
{
cerr<<"An error occurred while trying to open the file "<<argv[1]<<endl;
return 1;
}
while(!inFile.eof())
{
inFile.getline(buff, sizeof(buff)); // needed to move to next line
lineCount++;
}
lineCount--; // The loop above will always run once to many.
cout<<lineCount<<endl;
return 0;
}
1) Koden er selvfølgelig forholdsvis simpel, men vil I mene at kommentarerne er tilpas. Der er ikke unødige eller manglende oplysninger?
2) Jeg sad og blev lidt irriteret over at while-loopet kører en gang for meget. Er der en forklaring på dette?