I now want to output results of some functions to an output file. I have one function that is suppose to count the words in the file but it isnt working
I have a test file with two lines in it.
Expand|Select|Wrap|Line Numbers
- abc def ghi gk
- ades
this is my program code.....
Expand|Select|Wrap|Line Numbers
- #include <iostream>
- #include <iomanip>
- #include <fstream>
- #include <string>
- using std::cin;
- using std::cout;
- using std::cerr;
- using std::ifstream;
- using std::ofstream;
- using std::setw;
- using std::string;
- void word_count(ifstream&, ofstream&);
- int main(int argc, char* argv[])
- {
- //if command line doesnt have 2 arguments output error message.
- if(argc < 2)
- cout << "error need more arguments.";
- while(argc > 1)
- {
- //output each command line argument.
- for(int idx = 0; idx < argc; ++idx)
- {
- //put file name in a c string.
- string arg(argv[idx]);
- // Define object for input
- ifstream in(arg.c_str());
- if(!in)
- {
- // couldn't open input file, exit
- cerr << "Error: couldn't open "
- << arg
- << " exiting\n";
- exit(1);
- }
- // create name of output file
- string out_file_name = arg + ".COPY";
- // Define object for output
- ofstream out(out_file_name.c_str());
- if(!out)
- {
- // couldn't open output file, exit
- cerr << "Error: couldn't open "
- << out_file_name
- << " exiting\n";
- exit(1);
- }
- // Output
- const int WIDTH = 4;
- int count = 1;
- string input_string;
- while (in >> input_string)
- {
- word_count(in, out);
- // one word per line
- out << setw(WIDTH) << count << ": "
- << input_string << "\n";
- ++count;
- }
- // Close files
- in.close();
- out.close();
- return 0;
- }}
- }
- //fuction definitions
- void word_count(ifstream&, ofstream&)
- {
- int counter = 0;
- while (!eof)
- {
- string words;
- cin >> words;
- ++counter;
- }
- cout << counter << "\n";
- }
Expand|Select|Wrap|Line Numbers
- 1: ^?ELF^A^A^A^@^@^@^@^@^@^@^@^@^B^@^C^@^A^@^@^@¼<8c>^D^H4^@^@^@^@^Z^@^@^@^@^@^@4@^
- 2: ^@^H^@(^@^^^@^[^@^F^@^@^@4^@^@^@4<80>^D^H4<80>^D^H^@^A^@^@^@^A^@^@^E^@^@^@^D^@^@^@^C^@^@^@4^A^@^@4<81>^D^H4<81>^D^H^S^@^@^@^S^@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