C: How to convert int string to actual ints and store them in an array?

I have a line "14 22 33 48". I need to insert each of the values ​​into a string at the corresponding location in the array:

int matrix[5];

so that

matrix[0] = 14;
matrix[1] = 22;
matrix[2] = 33;
matrix[3] = 48;

How to do it?

+3
source share
5 answers

Robust string handling in C is never easy.

Here is the procedure that immediately appeared for me. Use strtok()to split a string into separate tokens and then convert each token to an integer value with strtol().

: strtok() ( 0 ). , . , strtok(). , strtok() , .

, strtol() ; , . - , 0, , , .

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

/**
 * Convert a space-delimited string of integers to an array of corresponding
 * integer values.
 *
 * @param str     [in]  -- input string
 * @param arr     [in]  -- destination array
 * @param arrSize [in]  -- max number of elements in destination array
 * @param count   [out] -- number of elements assigned to destination array
 */
void stringToIntList(char *str, int *arr, size_t arrSize, size_t *count)
{
  /**
   * The token variable holds the next token read from the input string
   */
  char *token;

  /**
   * Make a copy of the input string since we are going to use strtok(),
   * which modifies its input.
   */
  char *localStr = malloc(strlen(str) + 1);
  if (!localStr)
  {
    /**
     * malloc() failed; we're going to treat this as a fatal error
     */
    exit(-1);
  }
  strcpy(localStr, str);

  /**
   * Initialize our output
   */
  *count = 0;

  /**
   * Retrieve the first token from the input string.
   */
  token = strtok(localStr, " ");
  while (token && *count < arrSize)
  {
    char *chk;
    int val = (int) strtol(token, &chk, 10);
    if (isspace(*chk) || *chk == 0)
    {
      arr[(*count)++] = val;
    }
    else
    {
      printf("\"%s\" is not a valid integer\n", token);
    }

    /**
     * Get the next token
     */
    token = strtok(NULL, " ");
  }

  /**
   * We're done with the dynamic buffer at this point.
   */
  free(localStr);
}

int main(void)
{
  int values[5];
  char *str = "14 22 33 48 5q";
  size_t converted;

  stringToIntList(str, values, sizeof values / sizeof values[0], &converted);

  if (converted > 0)
  {
    size_t i;
    printf("Converted %lu items from \"%s\":\n", (unsigned long) converted, str);
    for (i = 0; i < converted; i++)
      printf("arr[%lu] = %d\n", (unsigned long) i, arr[i]);
  }
  else
  {
    printf("Could not convert any of \"%s\" to equivalent integer values\n", str);
  }

  return 0;
}
+1

sscanf:

sscanf(val, 
       "%d %d %d %d", 
       &matrix[0], 
       &matrix[1], 
       &matrix[2], 
       &matrix[3]
);
+8
const char *p = input;
int i = 0, len;
while (i < sizeof(matrix)/sizeof(matrix[0]) 
   && sscanf(p, "%d%n", &matrix[i], &len) > 0) {
    p += len;
    i++;
}

, ...

+5

I would recommend strtolthat provides better error handling than atoior sscanf. This version stops if it encounters a bad character or ends in space in an array. Of course, if the string does not have enough integers to fill the array, the rest will remain uninitialized.

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

#define ARRAY_SIZE 5

int main(int argc, char *argv[])
{
   /* string to convert */
   const char * str = "14 22 33 48";

   /* array to place converted integers into */
   int array[ARRAY_SIZE];

   /* this variable will keep track of the next index into the array */
   size_t index = 0;

   /* this will keep track of the next character to convert */
   /* unfortunately, strtol wants a pointer to non-const */
   char * pos = (char *)str;

   /* keep going until pos points to the terminating null character */
   while (*pos && index < ARRAY_SIZE)
   {
      long value = strtol(pos, &pos, 10);

      if (*pos != ' ' && *pos != '\0')
      {
         fprintf(stderr, "Invalid character at %s\n", pos);
         break;
      }

      array[index] = (int)value;
      index++;
   }
}
+2
source

the best way to convert an int string to actual ints and store them in an array.

#include<stdio.h>
#include<string.h>
#include<ctype.h>
int atoi1(char*,int,int);
void main(){
    char arr1[1000];
    int array[1000];
    gets(arr1);
    int i=0,j,k=0;
    while(i<strlen(arr1)){
        j=i+1;
        while(*(arr1+j)!=' ')
            j++;
        *(array+k)=atoi1(arr1,i,j-1);
        i=j+1;k++;
    }
}
int atoi1(char *arr1,int start,int end){
    char arr2[1000];int j=0,i;
    for(i=start;i<end+1;i++){
        *(arr2+j)=*(arr1+i);
        j++;
    }
    *(arr2+j)='\0';
    return atoi(arr2);
}
0
source

Source: https://habr.com/ru/post/1736543/


All Articles