Search code examples
arrayscstringstdin

How to split a char array into two diferent types in c?


So, I need to use the stdin to read a file that has two columns, the first one is a char, the second is an integer.

The input file is something like this:

i 10
i 20
i 30
i 40
i 50
i 45
r 48

My code currently:

int main(){
    char line[MAX];
    int n = 0;
    while(fgets(line, MAX, stdin)){
            printf("string is: %s\n",line);

    }
    return 0;

The output results in:

string is: i 10

string is: i 20

string is: i 30

string is: i 40

string is: i 50

string is: i 45

string is: r 48
 

So, what i need to do now is to assign an char array with the first column and an integer array with the second. Something like int V[size] = [10,20,30,40,50,45,48] and char W[size] = [i,i,i,i,i,i,r]. How can I do that?


Solution

  • Use sscanf() to parse the string and extract the data you want.

    #include <stdio.h>
    #include <stdlib.h>
    
    #define MAX 500
    
    int main(void)
    {
      int num[MAX] = {0}, lines = 0;
      char line[MAX] = {0}, sym[MAX] = {0};
    
      while (fgets(line, MAX, stdin))
      {
        if (lines >= MAX) /* alternative check comments */
        {
          fprintf(stderr, "arrays full\n");
          break; /* break or exit */
        }
    
        if (sscanf(line, "%c %d", &sym[lines], &num[lines]) != 2) /* check return value for input error */
        {
          /* handle error */
          exit(EXIT_FAILURE);
        }
    
        lines++;
      }
    
      for (int i = 0; i < lines; i++)
      {
        printf("char: %c | num: %d\n", sym[i], num[i]);
      }
    
      exit(EXIT_SUCCESS);
    }
    

    You may also use feof() and ferror() to determine if fgets() failed or you reached EOF .