Столкновение с проблемой (завершение программы и неправильное распределение) при обработке 2D-матрицы и ее сохранении пуC++

Программы на C++. Форум разработчиков
Anonymous
 Столкновение с проблемой (завершение программы и неправильное распределение) при обработке 2D-матрицы и ее сохранении пу

Сообщение Anonymous »

Я работаю над программой, которая читает CSV-файл, сохраняет его внутри 2D-матрицы, а затем снова читает и пытается отформатировать его в определенном стиле, выполняя операции форматирования. Пока я выполняю эти операции в это время, программа перестает выдавать ошибку.
Ошибка:

Код: Выделить всё

terminate called after throwing an instance of 'std::bad_alloc' what():  std::bad_alloc
Я ожидал, что программа полностью отсканирует 2D-матрицу, содержащую значения csv, и форматирование произойдет одновременно, и вся операция сканирования матрицы Csv и создания Отформатированная матрица будет выполнена.
Программа:

Код: Выделить всё

#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

// class Record {
// public:
//     string date;
//     string transactionDescription;
//     int credit = 0;
//     int debit = 0;
//     string currency = "INR";  // Set  Default to INR for domestic
//     string cardHolder;
//     string transactionType; // "Domestic" or "International"
//     string location;
// };

// Helper function to trim spaces from a string
string trim(const string& str) {
size_t first = str.find_first_not_of(' ');
size_t last = str.find_last_not_of(' ');
return (first == string::npos || last == string::npos) ? "" : str.substr(first, (last - first + 1));
}

string get_last_word(const string& str) {
// First, trim the input string
string trimmed_str = trim(str);

// Find the position of the last space
size_t last_space = trimmed_str.find_last_of(' ');

// If there is a space, return the substring after the last space
if (last_space != string::npos) {
return trimmed_str.substr(last_space + 1);  // Substring after the last space
}

// If there is no space, return the whole string (it is a single word)
return trimmed_str;
}

string get_last_word_and_remove(string& str) {
// Trim the string before processing
string trimmed_str = trim(str);

// Find the position of the last space
size_t last_space = trimmed_str.find_last_of(' ');

// If there is a space, extract the last word and remove it from the string
if (last_space != string::npos) {
string last_word = trimmed_str.substr(last_space + 1);  // Extract the last word
str = trimmed_str.substr(0, last_space);  // Remove the last word from the original string
str = trim(str);  // Trim the string again after removal of the word
return last_word;  // Return the last word
}

// If there is no space, the entire string is a single word
str = "";  // Clear the string as it's a single word
return trimmed_str;  // Return the whole string
}

bool is_valid_date(const std::string& date_str) {
string detected_format;
// Normalize the date by replacing different separators with '-'
std::string normalized_date = date_str;
for (char& c : normalized_date) {
if (c == '/' || c == '.') c = '-';  // Convert all separators to '-'
}

// Check if the normalized date has the correct length for a date (e.g., 10 characters: DD-MM-YYYY)
if (normalized_date.length() != 10) return false;

// Regular expressions for detecting the formats
regex dd_mm_yyyy_regex(R"(^(\d{2})-(\d{2})-(\d{4})$)");
regex mm_dd_yyyy_regex(R"(^(\d{2})-(\d{2})-(\d{4})$)");
regex yyyy_mm_dd_regex(R"(^(\d{4})-(\d{2})-(\d{2})$)");

std::smatch match;

// Check for YYYY-MM-DD format
if (std::regex_match(normalized_date, match, yyyy_mm_dd_regex)) {
detected_format = "YYYY-MM-DD";
return true;
}
// Check for DD-MM-YYYY format
if (std::regex_match(normalized_date, match, dd_mm_yyyy_regex)) {
detected_format = "DD-MM-YYYY";
return true;
}
// Check for MM-DD-YYYY format
if (std::regex_match(normalized_date, match, mm_dd_yyyy_regex)) {
detected_format = "MM-DD-YYYY";
return true;
}

// If none of the patterns match, it's not a valid date format
return false;
}

bool searchCharInVector(const vector& vec, char ch) {
// Traverse the vector
for (const string& str : vec) {
// Traverse each string in the vector
for (char c : str) {
// Check if the current character matches the input character
if (c == ch) {
return true;   // Return true if the character is found
}
}
}
return false;  // Return false if the character is not found
}

// Helper function to check if a string is a valid number
bool is_number(const std::string& str) {
if (str.empty()) return false;
for (char const &c : str) {
if (!isdigit(c) && c != '.') return false;  // Allow digits and decimal point
}
return true;
}

// Function to process CSV file and store the rows in a 2D vector
void processCSV(const string& file_name, vector& data) {
ifstream file(file_name);
string line;

// Check if the file opened successfully
if (!file.is_open()) {
cerr 

Подробнее здесь: [url]https://stackoverflow.com/questions/79053956/facing-issue-of-prog-termination-and-bad-alloc-while-processing-2d-matrix-and[/url]

Вернуться в «C++»