May 20, 2013 at 9:43pm UTC
I am having trouble making the program open a file. What this program does is that it prompts the user for a file name so that it can open that file and count the number of chars, words and lines it contains (like when using the wc command). I'm coding it in a way where it keeps asking the user for another file name until the user hits ^C. Any suggestions?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;
main()
{
string word, line, fish;
int chars = 0, words = 0, lines = 0;
istringstream line_string;
cout << "Enter file name: " << line;
getline(cin, line);
while (!cin.eof())
{
ifstream myfile (line);
lines++;
chars += line.length() + 1;
line_string.str(line);
while (line_string >> word)
words++;
line_string.clear();
getline(cin, line);
cout << lines << ' ' << words << ' ' << chars << endl;
}
}
Last edited on May 20, 2013 at 9:57pm UTC
May 20, 2013 at 10:55pm UTC
You should
always put
int in front of the main function even if the compiler allows you to do it with out int.
maybe try something like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream> //std::cout , std::flush , std::endl
#include <fstream> //std::ifstream
int main()
{
std::string input = "" , info = "" ;
std::cout << "Please enter the filename.\n> " << std::flush;
std::getline( std::cin , input ); //best to use getline for strings not cin
std::ifstream in( input.c_str() )
while ( in.good() )
{
std::getline( in , info );
}
std::cout << info << std::endl;
}
http://www.cplusplus.com/doc/tutorial/files/
Last edited on May 20, 2013 at 10:55pm UTC