passing arguments to main

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-31 04:39:10

问题


I know this is fairly basic, but I'm still stuck. So I have a function that needs to take in a variable n, so this is my main function

int main(int argc, char* argv){
  sort(argv[1]);
    }

And I'm calling the program like this:

    ./sort 4 <text.txt

But the number 4 doesnt get recognized or passed into the function. What am I doing wrong? I know that argv[0] should hold the name of program itself and each one from there on should hold the arguments.


回答1:


You should try to print them all.

#include <stdio.h>

int main(int argc, const char *argv[])
{
    int i = 0;
    for (; i < argc; ++i) {
        printf("argv[%d] = '%s'\n", i, argv[i]);
    }
    return 0;
}

Running that code with ./a.out 4 < /somefile gives me:

argv[0] = './a.out'
argv[1] = '4'

Eventually you'll have to remember that the '4' is a pointer to an array of characters, and you might have to parse it into an integer.




回答2:


char *argv is not correct. You get passed an array of char* ("Strings"), so the correct way to declare main would be int main(int argc, char *argv[]) or equivalently int main(int argc, char **argv) (in the latter case the array-argument is effectively converted to a pointer to the first element of the array).

What you are retrieving in the current version of the code is the second char in the array of argument-pointers given to you by the environment reinterpreted as an array of characters, which is something else entirely.




回答3:


As described by other you know how to get all argument, but not the "<text.txt".

This is not an argument to your program, but to the shell. This is input redirection, meaning that the input of the file is coming to the program as if it come from stdin (the keyboard).

To prevent this, just call you program like this:

./sort 4 text.txt

I am not sure what the function "sort" is, that you are calling.



来源:https://stackoverflow.com/questions/9242415/passing-arguments-to-main

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!