Hello joe809,
I think that you may be misunderstanding the command line arguments.
"argv[0]" is always the file name of the program and "argc" is always one to go with "argv[0]".
When VS runs it will set "argv[0]" to the program name and "argc" to one.
Should you have a command line like
progName this is a file name.txt
"argv[0] is the progName, arg[1] is "this, argv[2] is "is", argv[3] is "a", argv[4] is "file" and srgv[5] is "name.txt". And argc would equal 6.
Should you have a command line like
progName "this is a file name.txt"
. Then argv[0] is the program name and argv[1] is "this is a file name.txt" and argc would equal 2.
In your program on line 6 if "argc" is not equal to one you will by pass the if statement and skip the for loop, which I am having a hard time understanding what it is for.
This may not be what you are looking for, but may give you an idea of how the "arg"s work.
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 43 44 45 46 47 48 49 50 51 52
|
#include <iostream>
#include <string>
#include <fstream>
int main(int argc, char* argv[])
{
std::string str;
std::ifstream file;
if (argc > 2)
{
std::cout << "\n To much input!\n";
//for (int i = 1; i < argc; i++)
//{
// str = argv[i];
// file.open(argv[i]);
// if (str.find(argv[i]))
// {
// if (str.find(" ") == std::string::npos)
// {
// std::cout << "Error, too many files" << std::endl;
// return 1;
// }
// }
//}
}
file.open(argv[1]);
if (!file)
{
std::cout << "\n File \"" << argv[1] << "\" did not open!\n";
return 1;
}
// <--- Used for testing. Not aactually needed.
else
std::cout << "\n File \"" << argv[1] << "\" successfully opened!\n";
std::getline(file, str);
file.close();
std::cout << "\n " << str << std::endl;
return 0;
}
|
BTW do not use "exit()" use return. "exit()" is an unconditional exit from the program and does not allow for things to close properly. Like closing the file or freeing memory created by the string class along with destroying the string object.
On the other hand since you open the file stream with "argv[1]" it really does not matter if there is anything else on the command line unless you want to use it later.
VS does have a way to provide command line arguments to run your program through the IDE. If you do not know how to use this feature I will help you through it.
Andy