Reputation: 105
I am new to C++ and I am learning with Visual Studio. I want to make a small program that reads a text from the command line and opens the text. I know that my program has to start like this:
int main (int argc, char *argv[] ){
ifstream File( argv[1] )
But I am super confused on how to run it from the Visual Studio Command Prompt. I know there are a lot of questions like this but I still haven't found what I am looking for. I read that you have to go to properties, Debug and change the command line arguments, but what exactly do I need to put in there? And what should I type in the VS Command Prompt.
Thank you!
Upvotes: 1
Views: 8847
Reputation: 8313
From menu find: Project->Properties. Or from the Solution Explorer tree right click on the project and select Properties.
Now, in the opened dialog left pane select: Configuration Properties->Debugging
Then in the right pane grid find the line titled: Command Arguments
Fill it with the input file name (I think you better put it there as a full path, if there is a space in the path use with double quotas. like this:
Without space:
filepathwithoutspace.txt
or with spaces:
"file path with spaces.txt"
Good luck.
Upvotes: 3
Reputation: 153909
For starters, your code should not start like that: before
passing argv[1]
to std::ifstream::ifstream
, you should
verify that there is an argument, and output an error message
otherwise. As it is, you could end up passing a null pointer to
the constructor of ifstream
, which will result (normally) in
a program crash.
As to how to run it: where did you put the executable? If
you're in the Visual Studio Command Prompt window, and have
invoked cl
, then by default, the executable should be in the
local directory. Just enter .\name
, where name
is the name
of your program. If you've actually compiled it from within the
IDE, then in the command window, you should use cd
to navigate
to where the executable was generated (which you can find out
from your properties), and invoke it as above; or you can simply
specify the path completely:
c:\Users\me\whereeverIPutTheThing\name
.
If you want to debug (using the debugger), you need to specify:
1) the name of the executable (but the default should be good),
2) the parameters to pass it (what you want to see in
argv[1]
—don't forget the quotes if it has a space in
it), and 3) the directory where the executable should run. The
second and third are somewhat interdependant: you can, for
example, specify just the filename in 2, and the path where the
file is located in 3, or you can specify the complete path to
the filename in 2, and forget about 3. Or use a combination of
the two: in practice, I tend to do everything from the root
directory of the project, so I'd specify a path relative to this
directory, and then the path from my project file to this root
in 3. (The way we have things set up, this is ..\..\..
, but
I think you'll find it somewhat shorter.)
Upvotes: 2