简体   繁体   中英

C: Structuring input with scanf()

Is there a way to control how scanf() separates input?

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. 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

To split on multiple characters you can use 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. 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/

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 . 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. also, fgets returns null with ctrl+c and sscanf returns the number of successful reads. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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