Line count directory input problem

hi,

this code works fine, it counts lines as it should, but here i have the path already specified and what i want is that user could do that - so how can i do that? Ive tried with string and cstring input, but i get a conversion error.

code:
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
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
	int lines = 0;

	cout << "Enter a text file: ";
	
        //string directory = "";             THIS
	//cin >> directory;                  WONT
	//ifstream inFile(directory);        WORK


	ifstream inFile("C:/a.txt");

	if( inFile )
	{
	string garbage;
	while( !inFile.eof() )
	{
	getline( inFile, garbage);
	lines++;
	}
	}
	else
	cout << "Open error" << endl;


	cout << "c:/a.txt contained " << lines << " lines." << endl;
	
}


ty in advance!
closed account (oG8U7k9E)
...
Last edited on
As above, use the c_str() member function of string.

You could also enter it at the command line.

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
#include <iostream>
#include <fstream>
using namespace std;

int main(int argc, char *argv[])
{
	int lines = 0;

	if (argc != 2)
        {
                // assuming your program is named linecount
                cout << "Usage: linecount [filename]" << endl;
                return 1;
        }

	ifstream inFile(argv[1]);        

	if( inFile )
	{
	string garbage;
	while( !inFile.eof() )
	{
	getline( inFile, garbage);
	lines++;
	}
	}
	else
	cout << "Open error" << endl;


	cout << argv[1] <<" "<< lines << " lines." << endl;
	
}


Edit: typo.
Last edited on
tnx audit, yea thats what i was looking for :) i tried type conversion but not like that

Chewbob, your version wont work - the program terminates at the beginning, did you forgot something?
I forgot to include <string> but that's just because I copied the code above but that wouldn't cause the program to terminate at the beginning. Are you running it correctly by typing the name of the executable followed by the name of a file? For example, for a file called file.txt and the executable I'll call linecount, I would type
linecount file.txt
...maybe this helps
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
char z;
int linecount = 0;

ifstream inData("a.txt");

while( !inData.eof())
{
    cin.get(z);
    cout << z ;
    cout << endl;

    if ( z == "\n" )
        linecount++;
}

cout << "\nthe input file contained " << linecount << " lines." << endl;
Topic archived. No new replies allowed.