Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Aug 20th, 2005, 12:01 PM   #1
coldDeath
Expert Programmer
 
coldDeath's Avatar
 
Join Date: Aug 2005
Location: UK
Posts: 862
Rep Power: 4 coldDeath is on a distinguished road
Send a message via AIM to coldDeath Send a message via Yahoo to coldDeath
Post Arguments in C++

Command line arguments in C++

This small tutorial will guide you through command line arguments in C++. It assumes you have at least basic knowledge of C++. If there is something unclear in this tutorial, private message, e-mail or instant message me with the details in my profile.

What is a command line argument?
An argument that the operating system passes to the main function in a C++ program. When the program is run from a console.

How do I run a program from a console?
It depends on your Operating System (OS).

Windows:
Compile your C++ program to an executable, then put it in a folder that is in the environmental variables path. If you don't know what this is, don't worry, you can just put your program into the C:/ directory. Then once in place, you must open the MS DOS prompt, you can do this by going: Start>Run and type cmd and press enter. You can get to the run prompt by using the windows key + r. From here if it says C:/> then you can run your program by typing in the filename and pressing enter. You do not need to add the .exe ending onto it. If you don't see the C:/> prompt, don't worry. Just type in this command and hit return: cd C:/ , then it should look like C:/>.

Linux(recommended :p):
Open the terminal (if you don't know how to do that, then I don't think you should use linux ) cd to the directory with the source code in it. For example: cd /home/jack/cpp/myfile.cpp then to use the G++ compiler to compile it type: g++ myfile.cpp this then makes a file called a.out, you can rename it if you like. a.out is an executable, so you can run it by typing ./a.out. If you dont want to put the ./ in front you can put the a.out file into /usr/bin, that way you only have to type the filename to run the program.

Ok i can run my program now, how do i add arguments?
Simply, when you run your program type the filename then a space then the argument. The syntax is:
filename argument1 argument2
you can use as many argument as you like.

How do i let my program accept these arguments?
Follow the tutorial below .

Tutorial
Ok, when you run a program with an argument, how do you let the operating system send it to the program? Well thats easy, you just have to give the main function two arguments. One of these is an integer variable that will contain the number of arguments, another is an array that holds all the different arguments.
Syntax of main function using arguments:
int main(int argc, char *argv[]){
    //code
}
See, easy, now your program can access the array as usual, whenever you want to use the argument you just have to use the variable:
argv[index number of argument]

Remember: arrays indexes start at 0!

ok here is an example:
#include <iostream> 
using namespace std; 
int main(int argc, char *argv[]){ 
    int i; 
    i = 0; 
    cout<<"There were "<<argc<<" arguments.\n"; 
    cout<<"They were:\n";
    while(i != argc){
        cout<<argv[i]<<"\n";
        i += 1;
}
    return 0;
}

That program will tell you how many arguments you gave the program and it will say what the arguments were.

Here is a pratical example of using command line arguments:
#include <iostream>
#include <fstream> // file handling capabilities
using namespace std;
int main(int argc, char *argv[]){
    if (argc != 2){
        cout<<"please provide one argument\n";
}else{
        ifstream my_file(argv[1]);
        if (!my_file.is_open()){
            cout<<"File couldn't be opened\n";
}else {
            char x;
            while (my_file.get(x)){ //returns false when reaches EOF
                cout<< x;
}
            my_file.close();
}
}
    return 0;
}
It reads and displays the contents of the file that you put as the argument.

I hope you understand how command line arguments work and that you will use them in the future.
ColdDeath.
coldDeath is offline   Reply With Quote
Old Aug 20th, 2005, 2:17 PM   #2
proghelper
Newbie
 
Join Date: Jun 2005
Posts: 16
Rep Power: 0 proghelper is on a distinguished road
This is a very useful set of notes on the command line arguments. Well Done

_______________

Programming ( Assignment / Project ) Help
proghelper is offline   Reply With Quote
Old Aug 20th, 2005, 2:21 PM   #3
coldDeath
Expert Programmer
 
coldDeath's Avatar
 
Join Date: Aug 2005
Location: UK
Posts: 862
Rep Power: 4 coldDeath is on a distinguished road
Send a message via AIM to coldDeath Send a message via Yahoo to coldDeath
thanks,
please can a mod or an admin change the title of this topic to something more appropriate, such as: C++ Command Line Arguments Tutorial.
Because at th moment it looks liek its a question requiring help
thanks.
__________________
Join us at #programmingforums @ irc.freenode.net!

My software never has bugs. It just develops random features.
coldDeath is offline   Reply With Quote
Old Aug 20th, 2005, 2:24 PM   #4
DaWei
Resident Grouch
 
DaWei's Avatar
 
Join Date: Jun 2005
Posts: 6,453
Rep Power: 10 DaWei is on a distinguished road
Somewhat of an oversimplification, and probably belongs in the tutorial section. If you plan to write for a critical audience, I'd also suggest a spelling and grammar checker as a minimum. Sorry to seem critical, but one hopes it'll goad you in the proper direction. Writing is fun and builds credentials if you publish; editors are highly critical and rejections are the norm, not the exception.
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code.
Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers
DaWei is offline   Reply With Quote
Old Aug 20th, 2005, 2:28 PM   #5
coldDeath
Expert Programmer
 
coldDeath's Avatar
 
Join Date: Aug 2005
Location: UK
Posts: 862
Rep Power: 4 coldDeath is on a distinguished road
Send a message via AIM to coldDeath Send a message via Yahoo to coldDeath
You cannot post in the tutorial section, a mod must move it there

Thanks for being critical, i like that, it helps m improve and make my work more readable and interesting. I see i have a few typos, but i can't see that there is anythign wrong with my grammar.
__________________
Join us at #programmingforums @ irc.freenode.net!

My software never has bugs. It just develops random features.
coldDeath is offline   Reply With Quote
Old Aug 20th, 2005, 2:45 PM   #6
DaWei
Resident Grouch
 
DaWei's Avatar
 
Join Date: Jun 2005
Posts: 6,453
Rep Power: 10 DaWei is on a distinguished road
Quote:
Compile you C++ program
A grammar checker will catch that, a spell checker won't, despite the fact that it's actually just a typo.
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code.
Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers
DaWei is offline   Reply With Quote
Old Aug 20th, 2005, 2:54 PM   #7
coldDeath
Expert Programmer
 
coldDeath's Avatar
 
Join Date: Aug 2005
Location: UK
Posts: 862
Rep Power: 4 coldDeath is on a distinguished road
Send a message via AIM to coldDeath Send a message via Yahoo to coldDeath
ok i see, thanks.
the edit button shouldn't dissappear >
__________________
Join us at #programmingforums @ irc.freenode.net!

My software never has bugs. It just develops random features.
coldDeath is offline   Reply With Quote
Old Aug 22nd, 2005, 9:07 AM   #8
Infinite Recursion
Programming Guru
 
Infinite Recursion's Avatar
 
Join Date: Jul 2004
Location: United States
Posts: 3,467
Rep Power: 8 Infinite Recursion is on a distinguished road
Send a message via MSN to Infinite Recursion Send a message via Yahoo to Infinite Recursion
nice work.
__________________
http://jasonpowers.net

"There are a thousand hacking at the branches of evil to one who is striking at the root."
Infinite Recursion is offline   Reply With Quote
Old Aug 22nd, 2005, 11:42 AM   #9
Scorpions4ever
Programmer
 
Join Date: Jun 2005
Posts: 86
Rep Power: 4 Scorpions4ever is on a distinguished road
You might want to mention that argv[0] is the name of the program itself. Also, the code indentation might need some work .
Scorpions4ever is offline   Reply With Quote
Old Aug 22nd, 2005, 11:58 AM   #10
thomas41546
Newbie
 
thomas41546's Avatar
 
Join Date: Aug 2005
Location: Alberta, Edmonton
Posts: 16
Rep Power: 0 thomas41546 is on a distinguished road
Send a message via MSN to thomas41546
coldDeath sweet tutorial,
it helped me understand how arguments work in c++.

Definitely going to save this somewhere on my C drive.
__________________
My website: http://68.149.191.84
Don't you wonder what this says?
Make sure you strip the code, of "\n".
V293LCBJIGNhbid0IGJlbGlldmUgeW91IGFyZS
ByZWFkaW5nIHRoaXMsIGdvb2Qgam9iIDopIGF
uZCB2aXNpdCBteSB3ZWJzaXRlIGF0IGh0dHA6L
y82OC4xNDkuMjAzLjE0NCwgaXRzIG5vdCBhbHdh
eXMgdXAu
thomas41546 is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 12:15 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC