Arguments passed to the command line not printed and the program loops indefinitely [Ubuntu/C++]

I'm trying to implement a simple command line program that takes three arguments and prints them on the linux terminal

For example:
1
2
3
    >c++ exec.cpp
    
    >./a 32 + 32


Should print out contents like this

32

+

32

But the program is looping indefinitely

I've implemented a check for argc
Like this

1
2
3
4
    if(argc!=3) {
    cout << "Exit" << endl;
    return -9999;
    }

In case the argument count is 3

These lines of code should be executed

1
2
3
4
5
    else {
    for(int i=0;i<argc;i++){
    cout << argv[i] << endl;
    }
    }

But as I explained before the program loops indefinitely

Here's the entire code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    #include <iostream>
    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <stdio.h>
    #include <string>
    
    using namespace std;
    
    int main(int argc,char* argv[]) {
     if(argc!=3) {
        cout << "Exit" << endl;
        return -9999;
        }
    else {
        for(int i=0;i<argc;i++){
        cout << argv[i] << endl;
        }
        }
    }

Last edited on
argv[0] contains the name of your program.
Three arguments would go in argv[1], argv[2], argv[3].
argc should be 4, not 3.

Explore what happens in your code if you enter just 2 arguments:
./a 32 +
Loops indefinitely? I can't see why that happens, but note that your test case is misleading.
./a 32 + 32

argc for this input is 4. The name of the program is the first argument normally.

Your code (once I take out the incorrect argc check) works correctly on an online compiler like onlinegdb
https://www.onlinegdb.com/online_c++_compiler

I still can't see why that would infinitely loop. Perhaps your shell is interpreting the output of "./a" as another call to the program? That would be very strange, though.

Edit: When it loops infinitely, does it print anything?
Try putting another print statement before the loop.
Last edited on
Registered users can post here. Sign in or register to post.