I have the following task:
Write a program that reorders the command-line argument array argv[], placing all strings that start with '-' first, followed by all other strings.
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
char* aux;
printf("Program name is %s\n", argv[0]);
if(argc == 1)
printf("Program called with no arguments.");
else
{
for(int i = 1; i < argc; i++)
{
if(argv[i][0] == '-')
{
aux = argv[i];
argv[1] = aux;
artv[i] = aux;
}
printf("Argument %d is: %s", i, argv[i]);
}
}
return 0;
}
For the command:
./a.out string1 -string2 string3 string4
Program name is ./a.out
Argument 1 is: string1
Argument 2 is: string1
Argument 3 is: string3
Argument 4 is: string4
So it basically copied argument 1 into argument 2, but I wanted to swap them. So I should've gotten:
Argument 1 is: -string2
Argument 2 is: string1
Argument 3 is: string3
Argument 4 is: string4
Am I getting the first character of each string correctly with argv[i][0]? I google'd this but I didn't find much.