Iterating with sscanf

女生的网名这么多〃 提交于 2019-12-02 23:19:10

问题


I do not know much about the sscanf function, but what I am trying to do is iterate through a line of integers. Given the variable

    char *lineOfInts

I have made this the line that registers the users input. I am able to get the input fine, but when I try to use sscanf, I want to iterate through every int. I know that I can account through all the ints if i know how many ints there will be before hand like this..

   sscanf(lineOfInts, "%d %d %d..etc", &i, &j, &k...) 

but what if I don't know how many integers a user will input? How can I account for all of the integers with just one variable? like

   sscanf(lineOfInts, "%d", &temp);
   //modifying int
   // jump to next int and repeat

thanks!


回答1:


Maybe something like that :

#include <stdio.h>

int main(void)
{
  const char * str = "10 202 3215 1";
  int i = 0;
  unsigned int count = 0, tmp = 0;
  printf("%s\n", str);
  while (sscanf(&str[count], "%d %n", &i, &tmp) != EOF) {
    count += tmp;
    printf("number %d\n", i);
  }

  return 0;
}  



回答2:


You can use strtol in a loop until you don't find the NUL character, if you need to store those numbers use an array:

#include <stdio.h>
#include <stdlib.h>

#define MAX_NUMBERS 10

int main(void) 
{
    char *str = "12 45 16 789 99";
    char *end = str;
    int numbers[MAX_NUMBERS];
    int i, count = 0;

    for (i = 0; i < MAX_NUMBERS; i++) {
        numbers[i] = (int)strtol(end, &end, 10);
        count++;
        if (*end == '\0') break;
    }
    for (i = 0; i < count; i++) {
        printf("%d\n", numbers[i]);
    }
    return 0;
}



回答3:


Read much more about sscanf(3) and strtol(3)

Notice that sscanf returns the number of scanned elements and accepts the %n conversion specifier (for the number of consumed char-s). Both are extremely useful in your case. And strtol manages the end pointer.

So you could use that in a loop...




回答4:


Use "%n" to record the count of characters scanned.

char *lineOfInts;

char *p = lineOfInts;
while (*p) {
  int n;
  int number;
  if (sscanf(p, "%d %n", &number, &n) == 0) {
    // non-numeric input
    break;
  }
  p += n;
  printf("Number: %d\n", number);
}


来源:https://stackoverflow.com/questions/32860697/iterating-with-sscanf

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