Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

Command line input in C gives error and works only for specific case

#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

question from:https://stackoverflow.com/questions/65940851/command-line-input-in-c-gives-error-and-works-only-for-specific-case

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

intput[j] = atoi(argv[i]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...