There was a question, I read the array from the file and sort it like this:

ifstream file("input.txt"); if (!file.is_open()) cout << "Файл не может быть открыт!"<<endl; else { int n, count = 0; while (file >> n) ++count; file.clear(); file.seekg(0, ios::beg); int * data = new int[count]; int * sort_data = new int[count]; count = 0; while (file >> n) data[count++] = n; cout << "Массив из файла:" << endl; for (int i = 0; i < count; i++) cout << data[i] << ' '; cout << endl; //////////////////////////////////// sort_mass(data, count); //////////////////////////////////// cout << "Отсортированный массив значений: " << endl; for (int i = 0; i < count; i++) cout << data[i] << " "; cout << endl; 

How to check for third-party characters, so that if it is in the file, something is not in this form: -3 15 5 10 16, issue a read error message or select the numbers from the recorded one and write them into an array

    1 answer 1

    Generally speaking, in your current program, if something different from an integer is encountered, the >> operator will transfer the stream to an invalid state and the while (first) loop will be interrupted. You just need to distinguish this situation from the normal end of the file (eof ()). But you will not know what is specifically wrong and cannot continue reading. If you want a more versatile option, you can do this:

    • read strings from the file (std :: string);
    • try to convert to an integer (for example, std :: stoi);
    • if it was possible - to accept the number in processing, otherwise - to display an error message and continue further;

    With this approach, you can read the entire file, process all the correct numbers and swear at all incorrect.

    And, by the way, if you use a vector (std :: vector) instead of a dynamic array, you can do everything in one pass (that is, read a string, convert to a number, if everything is OK, put in a vector), because the vector automatically increases size if necessary.