There is a task: there are only integers in the file, the number of these numbers is no more than 30 on one line (that is, the numbers can be on different lines), you need to remove the largest negative value from each line, while if all the negative numbers in the line are the same, there is one negative number in the line, then you don't need to delete anything.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
unsigned read_string(int*, FILE*);
void print(int*, unsigned, FILE*);
void remove_max_negative(int*, unsigned*);
int main() {
int values[30], s;
unsigned size, n = 1;
FILE* file = fopen("1.txt", "r");
if(!file){
printf("error);
return 1;
}
FILE* out = fopen("r.text", "w");
if(!out){
printf("error);
return 1;
}
while (size = read_string(values, file)) {
remove_max_negative(values, &size);
print(values, size, out);
}
fclose(file);
fclose(out);
remove("1.txt");
rename("r.txt", "1.txt");
return EXIT_SUCCESS;
}
unsigned read_string(int* values, FILE* stream) {
char value[1024];
unsigned result = 0;
fscanf(stream, "%s", value);
while (!feof(stream)) {
values[result] = atoi(value);
result++;
if (getc(stream) == '\n') return result;
fscanf(stream, "%s", value);
}
return result;
}
void print(int* values, unsigned size, FILE* output) {
for (int i = 0; i < size; i++) {
fprintf(output, "%d ", values[i]);
}
fprintf(output, "\n");
}
void remove_max_negative(int* values, unsigned* size) {
int max_value = -2147483648, flag = 0, index_max_value = -1;
for (int i = 0; i < *size; i++) {
if (values[i] < 0) {
if (values[i] > max_value) {
flag = 0;
max_value = values[i];
index_max_value = i;
}
else if (values[i] == max_value) {
flag = 1;
index_max_value = i;
}
else if (flag) {
index_max_value = i;
}
}
}if (index_max_value != -1) {
--* size;
for (int i = index_max_value; i < *size; i++) {
values[i] = values[i + 1];
}
}
}
If you enter:
1 2 -4 5 2 -4 6 -4 10 5 6 -7 -7 9 -8
Then the program, instead of removing the value I need, removes the most recent negative, regardless of what number is there. I did quite a lot of tests, but the only conclusion I made was that the error occurs not because of the number of numbers, but because of repeated negative values. I can't find any errors in the code myself