简体   繁体   中英

Input of varying format in C

I am currently trying to figure out how to process an input of such format: [int_1,...,int_N] where N is any number from interval <1, MAX_N> (for example #define MAX_N 1000 ). What I have right now is fgets to get it as string which I then, using some loops and sscanf , save into an int array.

My solution is, IMO, not the most elegant and functional, but that's because of how I implement it. So what I'm asking I guess is how you guys would solve this problem, because I've ran out of ideas.

Edit: adding the code for string -> int array

int digit_arr[MAX_N];
char input[MAX_N];

//MAX_N is a constant set at 1000
//Brackets and spaces have been removed at this point

for (i = 0; i < strlen(input); i++) {
  if(sscanf(&input[i+index_count],"%d,", &digit_arr[i]) == 1){
    while (current_char != ',') {
      current_char = input[i+index_count+j];
      index_count++;
      j++;
      if ((index_count+j+i) == strlen(input)-1){
        break;
      }
   }
}

My personal variant:

char const* data = input; // if input is NOT a pointer or you yet need it unchanged
for(;;)
{
    int offset = 0;
    if(sscanf(data, "%d,%n", digit_arr + i, &offset) == 1)
    {
        ++i;
        if(offset != 0)
        {
            data += offset;
            continue;
        }
    }
    break;
}

You might finally ckeck if all characters in the text are consumed:

if(*data)
{
    // not all characters consumed, input most likely invalid
}
else
{
    // we reached terminating null character -> fine
}

Note that my code as is does not cover trailing whitespace, you could do so by changing the format string to "%d, %n (note the added space character).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM