In this program, I am trying to get an input by using fgets and split this input by two halves when there is a " " - assumed that the user inputs in a "%d %d" fashion. Then, I am trying to store the first half in "keyPart" and the second half in "valuePart". Finally, I am aiming to convert these parts into int by using the atoi function.
However, when I execute the program, it is resulted with "Segmentation Fault".
Any problems you can spot?
Thank you.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define M 31
int main(void)
{
char unixRead[21];
int key;
int value;
int i = 0;
int j = 0;
int splitIndex;
char *keyPart;
char *valuePart;
int loopCondition = 1;
puts("Please enter a key and a value for that key, leaving a single space in between (%d %d).");
puts("The inputs which will not match the given template will cause problems and the program will not work.");
while (loopCondition == 1)
{
fgets(unixRead, 20, stdin);
while (unixRead[j] != ' ')
{
keyPart = strcat(keyPart, unixRead[j]);
j++;
}
j++;
while (unixRead[j] != '\0')
{
valuePart = strcat(valuePart, unixRead[j]);
j++;
}
key = atoi(keyPart);
value = atoi(valuePart);
printf("Key: %d, Value: %d", key, value);
}
return 0;
}