I'm trying to open a txt file using command line arguments in Visual C++. I know you need argc and argv[] in the main. What would be an example you would type into the text field on project>properties>debugging>command arguments? How would you display the text on screen? After reading the txt file, I need to sort it. That is another step I will deal with latter.

Thank you.

this is what I have so far. The comments are how I am interpreting the code.

#include <iostream>

using namespace std; 
   
int main(int argc, char* argv[])
		{
		  cout << "argc = " << argc << endl; //argc is the number of elements argv[] contains
											//if you enter more text into command arguments, argc will get larger
		  cout << "argv[0] = " <<argv[0] << endl; //argv[0] is the file name and location
		  cout << "argv[1] = " << argv[1] << endl; //argv[1] is the text entered into the text field
		}

Recommended Answers

All 3 Replies

Your comments in the code are spot on!

Here's how to use the argument to open a file and display it's contents:

#include <fstream> // for file-access
#include <string>
#include <iostream>

using namespace std; 

int main(int argc, char* argv[])
{ 
    if (argc > 1) {
        cout << "argv[1] = " << argv[1] << endl; 
    } else {
        cout << "No file name entered. Exiting...";
        return -1;
    }
    ifstream infile(argv[1]); //open the file
    
    if (infile.is_open() && infile.good()) {
        cout << "File is now open!\nContains:\n";
        string line = "";
        while (getline(infile, line)){
            cout << line << '\n';
        }
        
    } else {
        cout << "Failed to open file..";
    }
    return 0;
}

What you need to do is
- find a way to read from the file and get words instead of lines. (tip: look at the third argument of getline)
- store them all in a vector (
or another container)
- find a way to sort the vector. (don't make it too hard on yourself!)

Thank you for helping.What would you enter into the text field to make it know to use the file?

project>properties>debugging>command arguments

How about the path to the file? For example : "c:\test.txt"

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.