#include <stdio.h>
#include <stdlib.h>
int
main(
int
argc,
char
*argv[]) {
const
char
*filename = argv[1];
FILE
*fin =
fopen
(filename,
"r"
);
if
(fin != NULL) {
char
*first_value = NULL;
size_t
length_of_buffer = 0;
ssize_t bytes_read;
while
((bytes_read = getline(&first_value, &length_of_buffer, fin)) != -1) {
printf
(
"Data = '%s' : Length = %zu\n"
, first_value, bytes_read);
char
*second_value;
second_value = (
char
*)
malloc
(bytes_read *
sizeof
(
char
));
char
imaginary_flag[2] = {0, 0};
int
i, j = 0, k = 0;
char
met_a_number = 0;
char
copy_to_second_value = 0;
char
previous_character =
'\0'
;
for
(i = 0; i < bytes_read; i++) {
const
char
current_character = first_value[i];
if
(current_character ==
'j'
) {
if
(copy_to_second_value == 0) {
imaginary_flag[0] = 1;
}
else
{
imaginary_flag[1] = 1;
}
continue
;
}
if
(!(current_character ==
' '
|| current_character ==
'('
|| current_character ==
')'
)) {
if
(copy_to_second_value == 0) {
if
(current_character ==
'-'
|| current_character ==
'+'
) {
if
(met_a_number == 1 && previous_character !=
'e'
) {
copy_to_second_value = 1;
first_value[i] =
'\0'
;
second_value[k++] = current_character;
}
else
{
first_value[j++] = current_character;
}
}
else
{
first_value[j++] = current_character;
met_a_number = 1;
}
}
else
{
second_value[k++] = current_character;
}
}
else
{
if
(met_a_number == 1) {
copy_to_second_value = 1;
first_value[i] =
'\0'
;
}
}
previous_character = current_character;
}
if
(first_value[j - 1] ==
'\n'
) {
first_value[j - 1] =
'\0'
;
}
else
{
first_value[j] =
'\0'
;
}
second_value[k - 1] =
'\0'
;
double
numbers[2];
sscanf
(first_value,
"%lf"
, &(numbers[0]));
printf
(
"%.f = '%s' is imaginary = %s\n"
, numbers[0], first_value, imaginary_flag[0] == 0 ?
"FALSE"
:
"TRUE"
);
if
(copy_to_second_value == 1) {
sscanf
(second_value,
"%lf"
, &(numbers[1]));
printf
(
"%.f = '%s' is imaginary = %s\n"
, numbers[1], second_value, imaginary_flag[1] == 0 ?
"FALSE"
:
"TRUE"
);
}
free
(second_value);
double
real = 0, imaginary = 0;
if
(copy_to_second_value == 1) {
if
(imaginary_flag[0] == imaginary_flag[1]) {
fprintf
(stderr,
"Invalid input line.\n"
);
if
(imaginary_flag[0] == 0) {
fprintf
(stderr,
"None of the components is imaginary\n"
);
}
else
{
fprintf
(stderr,
"Both components are imaginary.\n"
);
}
continue
;
}
if
(imaginary_flag[0] == 0) {
real = numbers[0];
imaginary = numbers[1];
}
else
{
real = numbers[1];
imaginary = numbers[0];
}
}
else
{
if
(imaginary_flag[0] == 0) {
real = numbers[0];
}
else
{
imaginary = numbers[0];
}
}
printf
(
"Real part: '%f'\tImaginary part: '%f'\n"
, real, imaginary);
printf
(
"\n"
);
}
free
(first_value);
fclose
(fin);
}
else
{
fprintf
(stderr,
"Failed to open file '%s'\n"
, filename);
return
EXIT_FAILURE;
}
return
EXIT_SUCCESS;
}