使用sscanf为每个索引的int数组添加元素

时间:2015-09-30 12:43:19

标签: c arrays scanf

所以,我们有一个"机器问题"我们应该在哪里获得多项式的根。我的问题是:有没有办法将每个索引的元素添加到一个int数组。

这是我的代码(它只是一个功能顺便说一句)

void coeffunc(int degree){
     char coef[1000];
     int coefs[1000], i;

     printf("Enter %d integer coefficients starting from the 0th degree.\nSeparate each input by a comma: ", degree);
     fgets(coefs, 999, stdin);
     for(i=0;i!=degree;i++){
          sscan(coef, "%d[^,]", &coefs[i]);
     }

我对此代码的问题是,如果输入是一个字符,我不确定如何捕获错误。

1 个答案:

答案 0 :(得分:0)

使用"%n"保存已扫描字符的数量,以了解继续扫描的位置。

#include <stdio.h>
#define BUFSIZE 1000

void coeffunc(int degree) {
  char coef[BUFSIZE];
  int coefs[BUFSIZE / 2];  // Number of integer certainly less than < BUFSIZE/2

  printf("Enter %d integer coefficients starting from the 0th degree.\n"
      "Separate each input by a comma: ", degree);
  if (fgets(coef, sizeof coef, stdin) == NULL) {
    return;
  }
  static const char *format[2] = { 
      "%d %n",
      " ,%d %n" };
  char *p = coef;
  int i;
  for (i = 0; i < degree; i++) {
    int n = 0;
    sscanf(p, format[i > 0], &coefs[i], &n);

    // Catch potential error 
    if (n == 0) break;

    p += n;
  }

  // More error detection
  if (*p) Fail();  // Extra text on the line
  if (i < degree) Fail(); // No enough values
}

如果允许VLA(可变大小的数组)

,则采用另一种缓冲区大小方法
#include <stdlib.h>
// bit_width*log10(2) rounded-up and sign
#define INT_TEXT_WIDTH (sizeof(int)*CHAR_BIT/3 + 1 + 1)
// ", "
#define COMMA_SPACE 2
// \r\n\0
#define LINE_END 3
#define BUF_NEEDED(n) ((INT_TEXT_SIZE + COMMA_SPACE) * (n) + LINE_END)

void coeffunc(int degree) {
  int coefs[degree];
  // To cope with those who like lots of spaces, leading zeros, use a 2x buffer
  char coef[BUF_NEEDED(degree) *2];
  ...