0

Im trying to figure out how to read a file that is entered into the command line.

I tried using

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>

int main(int argc, char *argv[])
{
    std::string a;
    int b, c, d;
    std::cout << "please enter the name of the file: " << std::endl;
    std::cin >> a;
    std::cout << argv[1] << "\n" << argv[0];
    std::fstream info(argv[1], std::ios::in);
    info >> b >> c >> d;
    std::cout << b << " " << c << " " << d; 
    system("pause");
    EXIT_SUCCESS;
}

but it throws an out of bounds exception trying to access argv[1].
how would I access this normally? is there some trick I didnt learn?
the way our teacher explained this to us was that int main(int argc,char *argv[]) read inserted commands from the command line and that argv[0] was always the filename.

2
Contributors
3
Replies
20
Views
4 Years
Discussion Span
Last Post by Ancient Dragon
0

First check if you entered a filename on the command line, if you did then the value argc will be greater than 1.

Just make sure there are no spaces in the filename you enter either on the command line or for the prompt "Enter a filename" because cin stops reading at the first space. If you need spaces on the command line then put the string in quotes

c:>myprog.exe "c:\Program Files\filename.txt" <Enter key>

int main(int argc, char* argv[])
{
    std::string filename;
    if( argc > 1) 
    {
       filename = argv[1];
    }
    else
    {
        cout << "Enter a filename\n";
        cin >> filename;
    }
    ifstream in(filename.c_str());

    // rest of program does here
}

Edited by Ancient Dragon

0

I did, what I entered in the prompt when asked was info.txt no quotes or spaces, I had the file in with the files for code and it still wouldnt register argv[] past 0.

0

If you don't enter anything on the command line when you start the program then the value of argc will be 1 -- argv[0] is always (almost) the name of the program that's beging run -- and in that case there will be no argv[1].

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.