Dec 5, 2019 at 2:55pm UTC
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 Dec 5, 2019 at 2:56pm UTC
Dec 5, 2019 at 5:28pm UTC
Loops indefinitely? I can't see why that happens, but note that your test case is misleading.
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 Dec 5, 2019 at 5:41pm UTC