D
D
Dred Wolf2020-12-03 16:43:39
C++ / C#
Dred Wolf, 2020-12-03 16:43:39

How to detect "number is not real" exception?

In the txt file, you need to find out the number of real numbers written with a space. It is understood that there should be only real numbers (data from the sensor). If there is a word, an integer, an incorrect entry, how to determine this? Here is the calculation code:

void main() {
    setlocale(LC_ALL, "Rus");
    FILE* file;
    float num;
    int index = 0;

    file = fopen("C:/Users/.../input.txt", "a+");
    if (file  == NULL)
    {
        printf("Ошибка! Недопустимый объект гиперссылки\n");
        return 0;
    }
    else {
       
        while (fscanf(file, "%f", &num) == true) {
            printf("%f\n", num);
            index++;
        }
      
        fprintf(file, "\nКол-во: %d", index);
        fclose(file);
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jcmvbkbc, 2020-12-03
@jcmvbkbc

printf(file, "\nОшибка, недопустимые значения");
he wrote down a fragment of the message:
"stim values"
and why?

Because printf's first argument is a string, not a file.
fprintf(file, "\nОшибка, недопустимые значения");

But with this you ruined your original file.
And to the heap
fscanf(file, "%f", &num) == true

check for == 1. fscanf returns a number (of fields scanned), not a success indication.

C
CityCat4, 2020-12-03
@CityCat4

I'm not too fond of streaming I/O, so I always work with small files according to the same scheme - checked for availability - got size - requested memory - read - closed.
And then work according to this scheme:
Found a gap, remembered the place, blurted out '\0' here
From the current place to the remembered one, I did sscanf() (in order not to warm my head with recognition of the real number format, but strain stdio with this).
If sscanf did not return an error, this is a real number and a ++ counter, otherwise we do not touch the counter.
Moved the current location one byte further than the memorized location.
Returned to searching for a space if the line did not end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question