Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用sscanf迭代_C_Getline_Scanf - Fatal编程技术网

用sscanf迭代

用sscanf迭代,c,getline,scanf,C,Getline,Scanf,我对sscanf函数知之甚少,但我尝试的是迭代一行整数。给定变量 char *lineOfInts 我已经做了这一行,登记用户的输入。我能够很好地获得输入,但当我尝试使用sscanf时,我想迭代每个int。我知道,如果我知道前面会有多少int,我可以计算所有int sscanf(lineOfInts, "%d %d %d..etc", &i, &j, &k...) 但是如果我不知道用户将输入多少个整数呢?如何用一个变量计算所有整数?像 sscan

我对sscanf函数知之甚少,但我尝试的是迭代一行整数。给定变量

    char *lineOfInts
我已经做了这一行,登记用户的输入。我能够很好地获得输入,但当我尝试使用sscanf时,我想迭代每个int。我知道,如果我知道前面会有多少int,我可以计算所有int

   sscanf(lineOfInts, "%d %d %d..etc", &i, &j, &k...) 
但是如果我不知道用户将输入多少个整数呢?如何用一个变量计算所有整数?像

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

阅读更多关于和

请注意,
sscanf
返回扫描元素的数量并接受
%n
转换说明符(用于消耗的
char
-s的数量)。这两种方法在您的案例中都非常有用。和
strtol
管理结束指针


因此,您可以在循环中使用它…

您可以在循环中使用
strtol
,直到您找不到
NUL
字符,如果您需要存储这些数字,请使用数组:

#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;
}
#包括
#包括
#定义最大值为10
内部主(空)
{
char*str=“12 45 16 789 99”;
char*end=str;
整数[最大值];
int i,计数=0;
对于(i=0;i
可能是这样的:

#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;
}  
#包括
内部主(空)
{
const char*str=“10 202 3215 1”;
int i=0;
无符号整数计数=0,tmp=0;
printf(“%s\n”,str);
而(sscanf(&str[count],%d%n,&i,&tmp)!=EOF){
计数+=tmp;
printf(“编号%d\n”,i);
}
返回0;
}  
使用
%n”
记录扫描的字符数

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);
}

还有一种方法可以做到这一点。。你只想要
sscanf()
吗?你应该在这里询问之前使用RTFM。是的,我只想使用sscanf()。还有,什么是RTFM?STFW。我明白了。好吧,我已经阅读了手册,我仍然感到困惑,震惊。这就是我在这里发帖的原因。没有必要用你的刻薄态度来折磨我的帖子。
%d%n