Question

So i was finally able to get my transposition cipher to work. But i needed to be able to take in variables from command line arguments. For example my transposition table given by transposition[] is subject to change based on the inputs in the command line arguments, also given an npos in the command line it determine how many characters i shift in total. For example if i put in the command line "a.out fileinput.txt fileoutput.txt 2 4 2 4 0 1" it should make it so that my program recognizes there is only 4 variables in the transposition array and the numbers in the transposition array are "2 4 0 1". Basically, i just want to know if there is a way to take in numbers from the command line and then store them into an array (specifically transposition array). I have tried using sscanf to take in the different arguments in the command line but it seems to not be working.

UPDATED Current Code:

#include <stdio.h>

int main(int argc, char *argv[]){

char transposition[]={};
char input[256];

char ch;
int i, j, k, npos;

FILE *file1=fopen(argv[1], "r");
FILE *file2=fopen(argv[2], "w");

sscanf(argv[3], "%d", &npos);
for(i=0;i<npos;++i){
sscanf(argv[4+i], "%d", &k);
transposition[i] = k;
}

int len= sizeof(transposition);
char temp[len];

while(fgets(input,sizeof(input),file1)!=NULL){
i=0;
do {
for(j=0;j<len;j++){
    ch = input[i];
    if(ch != '\n' && ch != '\0'){
        temp[j] = ch;
        ++i;
    } else {
        temp[j] = ' ';
    }
}
if(temp[0] != '.')
    for(k=0;k<len;k++){
        fprintf(file2,"%c", temp[transposition[k]]);
    }
}
while(ch != '\n' && ch != '\0');
fprintf(file2,"\n");
}
return 0;
}

Original Working Code:

#include <stdio.h>

int main(int argc, char *argv[]){
char transposition[]={2,4,0,1,3};
char input[256];
int len= sizeof(transposition);
char ch, temp[len];
int i, j, k;

FILE *file1=fopen(argv[1], "r");
FILE *file2=fopen(argv[2], "w");

while(fgets(input,sizeof(input),file1)!=NULL){
i=0;
do {
    for(j=0;j<len;j++){
        ch = input[i];
        if(ch != '\n' && ch != '\0'){
            temp[j] = ch;
            ++i;
        } else {
            temp[j] = ' ';
        }
    }
    if(temp[0] != '.')
        for(k=0;k<len;k++){
            fprintf(file2,"%c", temp[transposition[k]]);
        }
}
while(ch != '\n' && ch != '\0');
fprintf(file2,"\n");
}
return 0;
}
Was it helpful?

Solution

...
sscanf(argv[4], "%d", &npos);
char transposition[npos];
...
for(i=0;i<npos;++i){
    transposition[i] = atoi(argv[5+i]);//atoi : <stdlib.h> or sscanf(argv[5+i], "%d", &k);transposition[i] = k;
}
...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top