1

Fairly new to programming, currently doing a project using FLTK and I want to have an Fl_Int_Input, and use that to create an if statement which depends on what the person types in, something along the lines of:

if(input->value()=='1'){do this;}

if(input->value()=='2'){do this;}

else{do this;}

However when I use 'value', which looking online seems to be the way to use char values in an if statement, an error occurs: ISO C++ forbids comparison between pointer and integer

I think it is because the value is a const char* rather than char. The code runs when I use

if(input->value()=="1"){do this;}

But even if I input 1 nothing occurs

How should I go about using this input to create an if statement?

Like I said I'm pretty new to all of this so I don't know what other relevant information you might need to help, I will try to provide whatever information you might need, these are my includes:

#include <iostream>
#include <sstream>
#include <string>

#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Check_Button.H>
#include <FL/Fl_Double_Window.H>
#include <FL/Fl_Output.H>
#include <FL/Fl_Input.H>
#include <FL/Fl_Int_Input.H>
#include <FL/Fl_Timer.H>

Typing the code on here, one thing I notice is that the '1' turns a red colour, which doesn't occur on my code, maybe that is relevant?

aleco34
  • 13
  • 2

2 Answers2

0

You'll need to learn how strings in C work. The reason if(input->value()=="1") doesn't work for you is because the == operator on char* values does a pointer comparison, not a string comparison.

A pointer to the memory allocated for your string is returned by FL_Input::value() but that is not the same memory location as the string literal "1", which is stored somewhere in your program's memory segment.

To do C-style string comparison you would do this:

if( 0 == strcmp( input->value(), "1" ) )

The strcmp function is available when you include <cstring>.

Another way to do this (but not very nice) is to copy that value into a temporary std::string object and use its overloaded operator==( const char *):

if( std::string( input->value() ) == "1" )

To use std::string, include <string>.

More reading:

paddy
  • 60,864
  • 6
  • 61
  • 103
  • Thank you for the very quick reply! Still getting my head around pointers so this was really helpful :) – aleco34 Jan 19 '16 at 04:41
0

Another way of doing this is by saving the value in a variable then using the variable in the if statement.

std::string input_value;
input_data = input -> value();
if (input_data =="1") //should be in a callback or some function 
{ do this ...}
else if (input_data == "0")
{ do this ...}
else
{ do this ...}

Hope I understood and answered your question

Maxfurry
  • 54
  • 9