command line big problem bug

Feb 22, 2017 at 10:16pm
I need to mamke my program use the command line to open the text file and compute the numbers of its contents
Last edited on Feb 23, 2017 at 1:48am
Feb 23, 2017 at 1:01am
It seems like you are intending to read the numbers from the text file named "Lab3Test.txt". If so, there is no need to use the command line parameters (argc, argv) at all.

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
#include <iostream>
#include <fstream>

using namespace std;

int main()
{   
    ifstream mean("Lab3Test.txt");
    if (!mean)
    {
        cout << "could not open input file\n";
        return 1;
    }
    
    double total = 0;
    double number;
    int count = 0;    
    
    // testing if i get the numbers from my text file
    
    while ( mean >> number )
    {    
        cout << number << " ";
        total += number;
        count++; 
        
        if (count % 10 == 0)
            cout << endl;
    }
      
    cout << endl;
    
    // doing the average of the numbers
    
    double avg = total/count;
    
    cout << "The average is " << avg << endl;

}
Feb 23, 2017 at 1:49am
only thing i dont understand is how do i use c++ to open my text file with command line
Feb 23, 2017 at 2:47am
how do i use c++ to open my text file with command line

First check that there are at least two parameters (count argc).
The first, argv[0] is the name of the current executing program.
The second, argv[1] is the first actual parameter entered on the command line. Use that as the file name.
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
#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char ** argv) 
{
    if (argc < 2)
    {
        cout << "Missing filename parameter\n";
        return 1;
    }
    
    ifstream fin(argv[1]);
    if (!fin)
    {
        cout << "Could not open file " << argv[1] << '\n';
        return 2;
    }
    
    string line;
    while (getline(fin, line))
        cout << line << '\n';
        
}


Or did you mean you want to create a new output file from the data entered on the command line? Something like this perhaps.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char ** argv) 
{
    ofstream fout("output.txt");
    
    for (int i=1; i<argc; ++i)
    {
        fout << argv[i] << '\n';
    }
        
}

Topic archived. No new replies allowed.