簡體   English   中英

將元素數量未知的字符串掃描到C中的int數組

[英]scan string with unknown number of elements to an array of int in C

我在用C語言編寫的程序中工作,我有一個由數字組成的char字符串:

5 13 12 7 3 0

我想對其進行掃描,然后將所有這些整數放入一個int數組中。 我怎么做? 這是使用sscanf的方法嗎?

我嘗試了以下代碼,但沒有成功:

 fgets(datatemp, N*3, stdin);

 k = 0; garb = 'c';
    while(garb != '\0'){
      garb = strtok(datatemp, " ");
      array[k] = garb;
      k++;
    }

注意:我必須在一個函數中使用它,該函數將對許多數據執行相同的操作,其中“ datatemp”字符串將具有未知數量的整數(並且只有整數)。

謝謝你的幫助。

// Adapted from strtok(3) example.

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

int
main(int argc, char *argv[])
{
  char *str1, *str2, *token, *subtoken;
  char *saveptr1,*saveptr2;
  int j;
  char datatemp[ 120 ];
  char delim = ' ';

  fgets(datatemp, 119, stdin);

  /*
   * strtok has to be called with a pointer to the input
   * the first time then with a pointer to the string
   * subsequently
   */

  for(j=1, str1 = datatemp;; j++, str1 = NULL)
  {
    token = strtok_r(str1, &delim, &saveptr1);

    if(token==NULL)
      break;

    for (str2 = token; ; str2 = NULL)
    {
      subtoken = strtok_r(str2, &delim, &saveptr2);
      if (subtoken == NULL)
        break;
      printf(" --> %s\n", subtoken);
    }
  }

  exit(0);

}

我建議在循環中使用strtol ,速度更快(無中間緩沖區的直接轉換),並且可以檢查錯誤

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

int main(void)
{
    char s[128], *p, *q;
    int i, n, *v;

    /* get user input */
    fgets(s, sizeof s, stdin);
    /* count integers */
    for (p = s, n = 0; ; p = q, n++) {
        strtol(p, &q, 10);
        if (p == q) break;
    }
    v = malloc(sizeof(int) * n);
    /* populate array */
    for (p = s, i = 0; i < n; i++) {
        v[i] = strtol(p, &p, 10);
    }
    /* print array */
    for (i = 0; i < n; i++) {
        printf("%d\n", v[i]);
    }
    free(v);
    return 0;
}

您可以使用標頭<stdlib.h>聲明的標准函數strtol 例如

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


int main( void ) 
{
    char s[] = "5 13 12 7 3 0";
    size_t l = strlen( s );

    size_t n = 0;

    char *end_ptr = s;
    char **next_ptr = &end_ptr;

    errno = 0;

    while ( end_ptr != s + l )
    {
        strtol( *next_ptr, next_ptr, 10 );
        if ( errno != 0 ) break;
        ++n;
    }

    int a[n];
    memset( a, 0, n * sizeof( int ) );

    end_ptr = s;
    size_t i = 0;
    while ( end_ptr != s + l )
    {
        int value = ( int )strtol( *next_ptr, next_ptr, 10 );
        if ( errno != 0 ) break;
        a[i++] = value;
    }

    for ( i = 0; i < n; i++ ) printf( "%d ", a[i] );
    puts( "" );

    return 0;
}

輸出是

5 13 12 7 3 0

要按照OP的要求使用fgets()/sscanf() ,請參見下文。

sscanf()相比,使用fgets()/strtol()可提供更好的錯誤處理。 推薦strtol()

為了獲得最佳答案,OP需要提供諸如如何存儲數據(VLA,malloc,一次1個),錯誤處理問題等信息。

很難說出為什么由於缺少array[]的斷言而導致OP代碼不起作用,但是對於測試數據來說,它可能太小了,並且某些數據輸入的大小並沒有根據需要進行調整。

void foo() {
  char buf[100];
  if (fgets(buf, sizeof buf, stdin) == NULL) Handle_EOForIOError();

  int i = 0;
  int n = 0;
  int number;
  // Count the numbers
  while (sscanf(&buf[i], "%d %n", &number, &i) == 1) {
    n++;
  }

  int num[n];
  i = 0;
  int j;
  // scan again, this time save the numbers
  while (sscanf(&buf[i], "%d %n", &num[i], &j) == 1) {
    i = j;
  }

  // use the numbers
  bar(num, n);
}

上面的代碼可能會跳過j而使用while (sscanf(&buf[i], "%d %n", &num[i], &i) == 1); ,但我需要仔細檢查一些代碼點問題。

strtol()sscanf()更好。 要使用,建議一個輔助函數:

// return non-zero on failure 
static int user_strtoi(char **s, int *result) {
  char *endptr;
  errno = 0;
  long num = strtol(*s, &endptr, 10);
  if (endptr == *s) return 1; //  fail as nothing was parsed
  if (errno != 0) return 2; //  fail due to overflow
  if (num < INT_MIN || num > INT_MAX)  return 2; //  fail due to overflow
  *result = (int) num;
  *s = endptr;
  return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM