I have a problem of figuring out what I am asked to do and how to start. The problem is this:
Here's a simple help free challenge to get you started: write a program that takes a file as an argument and counts the total number of lines. Lines are defined as ending with a newline character. Program usage should be
count filename.txt
and the output should be the line count.
If you mean taking a file name as a command line argument, then that would be like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int main(int argc, char* argv[])
{
if(argc < 2) // checking to see if 2 arguments were passed from command line
{
cout << "TOO FEW ARGUMENTS\n";
return 0;
}
ifstream file(argv[1]); // delcare and open file
if(!file) // check if file opened
{
cout << "FILE NOT OPENED";
return 0;
}
When you run this on the command line, you'll have to pass in the file name as a command line argument. This will result in a total of 2 arguments passed in as the name of the program will automatically be inserted as the first argument (hence why we check for 2 arguments and argv[1] is the file name, because argv[0] is the program name).
Thank you guys. I'm still a bit confused. Ok, so I have int main(int argc, char *argv[], but what should I do with this? I'm a novice. so can please anyone explain in simple terms what take a file as an argument mean and what steps I need to do? I can't grasp how to take a file as an argument and then later count the total number of lines. Does this assignment include ifstream?
> What is command line? I'm confused.
If all your answers are "I am confused", I would recommend you take this easier approach. And I am sure your professor won't scold badly at you I think :)
> Hi,
>> How do you take a file as an argument?
> For example :
1 2 3 4
void readCountFile(std::string filename)
{
// Your code...
}
> And in your function main(), you call that function : readCountFile("input.txt");
Give me several minutes. I will give you some details later.
@aurimas13
Before that, can you prepare an input file with some random text (about several lines)? Then show the content of the file (even its file name) to us.
If all your answers are "I am confused", I would recommend you take this easier approach. And I am sure your professor won't scold badly at you I think :)
I think you will loose plenty of points for not doing what the assignment says.
@TheIdeasMan
A student should be at least aware of all small concepts before an assignment. Why would a professor force a student to solve such an assignment whereas the student doesn't even know (or has ever learned) what a "command line" is?
> To prepare an input file, should I simply use text editor, input words in the file and save as a .txt file?
Yes. You don't have to do this anymore :)