简体   繁体   English

C:使用scanf()构造输入

[英]C: Structuring input with scanf()

Is there a way to control how scanf() separates input? 有没有办法控制scanf()如何分离输入?

scanf("%10s %10s", array1, array2);

The above works fine, separating by space. 以上工作正常,按空间分隔。 But, can I use a different separation signal? 但是,我可以使用不同的分离信号吗?

Because neither of these seem to work if I want to splice input with a comma rather than a space: 因为如果我想用逗号而不是空格拼接输入,这些似乎都不起作用:

scanf("%10s,%10s", array1, array2);
scanf("%10s, %10s", array1, array2);

What gives? 是什么赋予了? A book I am reading claims that one can separate input with scanf() using any character, but fails to explain how to do so. 我正在阅读的一本书声称可以使用任何字符将输入与scanf()分开,但无法解释如何执行此操作。 Furthermore, if alternate characters can be used, can a broader criteria than a single character be used, too? 此外,如果可以使用替代字符,也可以使用比单个字符更广泛的标准吗? (ie value types, statements, etc.) (即价值类型,陈述等)

Using character classes: 使用字符类:

#include <stdio.h>

int main(int argc, const char **argv) {
  char s1[10], s2[10];
  const char *str = "word1,word2";
  sscanf(str, "%[^,],%s", s1, s2);
  printf("%s -- %s\n", s1, s2);
  return 0;
}

Or you can be even more specific: 或者您可以更具体:

sscanf(str, "%[^,],%[^,]", s1, s2);

which will also capture white space in s2 这也将捕获s2空白区域

To split on multiple characters you can use strstr : 要拆分多个字符,可以使用strstr

#include <stdio.h>
#include <string.h>
int main(int argc, const char **argv) {
  const char *str = "word1fooword2fooword3", *foo = "foo", *ptr;
  const char *eofstr = str;
  for (ptr = str; eofstr; ptr = eofstr + strlen(foo)) {
    char word[10];
    eofstr = strstr(ptr, foo);
    if (eofstr) {
      size_t len = eofstr - ptr;
      strncpy(word, ptr, len);
      word[len] = 0;
      printf("%s\n", word);
    } else {
      strcpy(word, ptr);
      printf("%s\n", word);
    }   
  }
  return 0;
}

You actually need to change the scanf's default delimeter. 您实际上需要更改scanf的默认分隔符。 And here is the exact answer to your questions. 以下是您问题的确切答案。

http://gpraveenkumar.wordpress.com/2009/06/10/how-to-use-scanf-to-read-string-with-space/ http://gpraveenkumar.wordpress.com/2009/06/10/how-to-use-scanf-to-read-string-with-space/

You can 'escape' the character delimiter using it between rect parentesis, but to be honest, I've never used that solution. 您可以在直肠排卵之间使用它来“逃避”角色分隔符,但说实话,我从未使用过该解决方案。 Instead, you can use fgets and sscanf . 相反,您可以使用fgetssscanf Is a more 'solid' way to do it, in my opinion. 在我看来,这是一种更“稳固”的做法。 fgets can read from the stdin and sscanf can look for commas and any other characters in the string. fgets可以从stdin读取,sscanf可以查找字符串中的逗号和任何其他字符。 also, fgets returns null with ctrl+c and sscanf returns the number of successful reads. 另外,fgets使用ctrl + c返回null,sscanf返回成功读取的次数。 Hope this helps. 希望这可以帮助。

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

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