Why doesn't this work?

Here is the exercise:
Write a program that does nothing except print all the commandline
arguments, each on a separate line.

Here is the code I made for this. It doesn't work though, I'm not getting errors it just prints the directory of the program instead of all the commandline arguments.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

using namespace std;

int main(int argc, char *argv[]){
    
    int a, i=0;
    
for (i;i<10;i++)
{
    cout << "Emter a number: ";
    cin >> a;
}    
for (int b=0;b<10;b++)
{
     cout << argv[b] << endl; 
     }
    system("PAUSE");
    return 0;
    }


How can I make this work right?
Why are you asking the user to input a number?

argc tells you how many commandline arguments there are. You don't need to get anything from the user.

Apart from that, you have the right idea with your 'b' loop, but you shouldn't loop to 10, you should loop to however many arguments there are.
Well I'm having a hard time understanding this command line argument part of the book really. How exactly do I get a commandline argument to print? Is the reason it prints the program directory because that's the only one? I'm just lost in this chapter. I've been doing fine on my own so far, but I really just need someone to explain this par
Last edited on
Also, argv[0] is not a command line argument so you might want to start at 1...
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

using namespace std;

int main(int argc, char *argv[]){
        
for (int b=1;b<10;b++)
{
     cout << argv[b] << endl; 
     }
    system("PAUSE");
    return 0;
    }


Okay, then is this right?
You want to start at one but you don't want to stop at 10, you want to stop at the last argument. So replace b<10 with b<argc.
Topic archived. No new replies allowed.