#include <stdio.h> #include <stdlib.h> // this code take input in cmd line , finds any integer input // and stores in an array int main (int argc,char *argv[]){ int intput[argc]; char * frstr = argv[0]; frstr=frstr+2; //removes ./ from filename while printing printf("%s ",frstr); int j=0; for(int i = 1;i<argc;i++) //loop to find integers and store in array intput { if( atoi(argv[i])>0) { j++; intput[i] = atoi(argv[i]); } printf(" %s ",argv[i]); } printf(" "); for (int i= 1; i<=j;++i ) // loop to print integers stored in intput { printf(" %d ",intput[i]); } printf(" "); return 0; }
I wrote this code to take input from cmd line and store any integer input in an array. This works fine if the cmd line inputs are all number but goes haywire as soon as any string input is there. Please help
Here's the problem:
intput[i] = atoi(argv[i]);
You use j to keep track of the number of elements in intput, but you're using i (which is the current element number argv) instead. You want:
j
intput
i
argv
intput[j] = atoi(argv[i]);
1.4m articles
1.4m replys
5 comments
57.0k users