c - Using sscanf to add an element to an int array per index -


so, have "machine problem" supposed obtain roots of polynomial. question is: there way add element per index int array.

here code(it's function btw)

void coeffunc(int degree){      char coef[1000];      int coefs[1000], i;       printf("enter %d integer coefficients starting 0th degree.\nseparate each input comma: ", degree);      fgets(coefs, 999, stdin);      for(i=0;i!=degree;i++){           sscan(coef, "%d[^,]", &coefs[i]);      } 

my problem code i'm not sure how catch error if input character.

use "%n" save count of scanned characters know continue scanning.

#include <stdio.h> #define bufsize 1000  void coeffunc(int degree) {   char coef[bufsize];   int coefs[bufsize / 2];  // number of integer less < bufsize/2    printf("enter %d integer coefficients starting 0th degree.\n"       "separate each input comma: ", degree);   if (fgets(coef, sizeof coef, stdin) == null) {     return;   }   static const char *format[2] = {        "%d %n",       " ,%d %n" };   char *p = coef;   int i;   (i = 0; < 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();  // text on line   if (i < degree) fail(); // no enough values } 

another buffer size approach if vla allowed (variable sized arrays)

#include <stdlib.h> // bit_width*log10(2) rounded-up , 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];   // cope lots of spaces, leading zeros, use 2x buffer   char coef[buf_needed(degree) *2];   ... 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -