简体   繁体   English

在C中接受来自命令行的输入

[英]Accepting Input from Command Line in C

How do I use scanf() IN C to accept multiple inputs from the command line? 如何使用scanf() IN C从命令行接受多个输入? I'm trying to get a name, followed by an arbitrary number of values from a user, on the same line. 我试图在同一行上获取一个名称,然后从用户那里获取任意数量的值。 I know the scanf() function is space/new line delimited. 我知道scanf()函数是用空格/换行符分隔的。

For example the user enters: dog 2 5 1 例如,用户输入:dog 2 5 1

I know scanf() will read the "dog", but how do I get it to read the following values. 我知道scanf()会读取“ dog”,但是如何获取它来读取以下值。 I can't use scanf("%s, %d, %d, %d", a, b, c, d) because there could be more than, or less than 3 values entered. 我不能使用scanf("%s, %d, %d, %d", a, b, c, d)因为可能输入的值大于或小于3。

You could pass arguments to the main function itself. 您可以将参数传递给main函数本身。 The prototype for main is 主要的原型是

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

You could use this to read the command line arguments. 您可以使用它来读取命令行参数。 argc gives the total number of arguments (separated by a space), and argv is a vector that holds it. argc给出参数的总数(以空格分隔),而argv是保存它的向量。

For example user will enter: ./yourExecutable dog 2 5 1 In this case the number of arguments would be 5 (including the name of your executable) and argv[0] would be your executable, argv[1] would be your "dog" and so on. 例如,用户将输入: ./yourExecutable dog 2 5 1在这种情况下,参数数量将为5(包括可执行文件的名称),而argv[0]将成为您的可执行文件,argv [1]将成为您的"dog"等等。

You can read the whole line to a string buffer using fgets() . 您可以使用fgets()将整行读取到字符串缓冲区。

Then split by spaces using strtok() . 然后使用strtok()按空格分隔。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM