简体   繁体   English

C 从控制台读取多个带有空格的单词/参数

[英]C read multiple words/arguments with space from console

Hi I am new to C and I want the user to type something like inspect 2 to show a value of an array at position 2 in that example.嗨,我是 C 新手,我希望用户输入类似inspect 2以显示该示例中位置 2 处的数组值。

I cant get it to work我无法让它工作

    char input[20];
    scanf("%s", input);

    if (strcmp(strtok(input, " "), "inspect") == 0) {
     char str[20];
     int idx;
     printf("input was %s", input);
     idx = sscanf(input, "%s %d", str, &idx);
   }

it always prints input was inspect but the following space and number are not read?它总是打印input was inspect但未读取以下空格和数字? What would be the right way to check if the user typed "inspect" and get the index he typed afterwards like I am trying to do?检查用户是否输入了“inspect”并获取他之后输入的索引的正确方法是什么?

thank you谢谢你

You have few choices, and you want to choose one and not mix them up.你的选择很少,你想选择一个而不是把它们混在一起。

For reading the input, consider using the fgets.要读取输入,请考虑使用 fgets。 Much safer, with fewer exceptions to deal with.更安全,处理的例外更少。 I've listed the equivalent sscanf, but it's much harder to use.我已经列出了等效的 sscanf,但它更难使用。 They will both bring in a complete line to 'input'.他们都将引入完整的“输入”行。 Notice that the fgets will also include the trailing new line.请注意, fgets 还将包括尾随的新行。

   // make buffer large enough.
char input[255] ;

if ( fgets(input, sizeof(input), stdin) != NULL ) {
   ...
}

// OR
if ( sscanf("%19[^\n]", input) = 1 ) {
} ;

For parsing: few options to parse the input` string.对于解析:解析输入字符串的选项很少。

Between the option, I would vote for the sscanf, as it provides the most validation and protection against bad input, overflow, etc. The strcmp(strtok(...)) can easily result in SEGV errors, when strtok returns NULL.在选项之间,我会投票支持 sscanf,因为它提供了对错误输入、溢出等的最大验证和保护。当 strtok 返回 NULL 时,strcmp(strtok(...)) 很容易导致 SEGV 错误。

Using sscanf使用 sscanf

  if ( sscanf(input, "inspect %d", &idx) ==1 ) {
     ... Show Element idx
  } ;

Using strtok/strcmp使用 strtok/strcmp

  if ( strcmp(strtok(input, " "), "inspect") == 0 ) {
      if ( sscanf("%d", strtok(NULL, " "), &idx) == 1 ) {
          .. Show element idx
      } ;
  } ;

Using strtol使用 strtol

  if ( strcmp(strtok(input, " "), "inspect") == 0 ) {
      char *stptr = strtok(input, " "), *endptr = NULL ;
      idx = strtol(stptr, &endptr, 10) ;
      if ( endptr != stptr ) {
          .. Show element idx
      } ;
  } ;

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

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