I’m encountering a segmentation fault issue in my FLTK program when attempting to calculate the average of numbers entered by the user.
I’ve tried debugging the program by adding print statements and checking pointer validity, but I’m unable to identify the root cause of the segmentation fault. I expected the program to calculate the average correctly without crashing, but it consistently throws a segmentation fault error.Here is my code:
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Input.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Output.H>
#include <vector>
#include <sstream>
#include <iomanip>
using namespace std; // Adding the 'using' directive to bring all symbols from the 'std' namespace into the global namespace
// Function to calculate average
double calculate_average(const vector<double>& numbers) {
if (numbers.empty()) {
return 0.0;
}
double sum = 0.0;
for (double num : numbers) {
sum += num;
}
return sum / numbers.size();
}
// Callback function for the "Add" button
void add_callback(Fl_Widget* widget, void* data) {
Fl_Input* input = (Fl_Input*)data;
Fl_Output* output = (Fl_Output*)((Fl_Button*)widget)->parent()->child(5); // Assumes output widget is at index 5
// Check for null pointers
if (!input || !output) {
return;
}
const char* input_value = input->value();
if (input_value && *input_value) {
double number;
istringstream iss(input_value);
if (iss >> number) {
vector<double> numbers;
istringstream iss2(output->value());
double num;
while (iss2 >> num) {
numbers.push_back(num);
}
numbers.push_back(number);
double average = calculate_average(numbers);
ostringstream oss;
oss << fixed << setprecision(2) << average;
output->value(oss.str().c_str());
}
}
input->value(""); // Clear input field after adding
}
int main() {
Fl_Window* window = new Fl_Window(400, 200, "Average Calculator");
// Input field for numbers
Fl_Input* input = new Fl_Input(150, 50, 200, 30, "Number:");
// Add button
Fl_Button* add_button = new Fl_Button(150, 90, 200, 30, "Add");
add_button->callback(add_callback, (void*)input);
// Output field for average
Fl_Output* output = new Fl_Output(150, 130, 200, 30, "Average:");
window->end();
window->show();
return Fl::run();
}