gpt4 book ai didi

c++ - FLTK - 在 if 语句中使用输入值 (const char*)

转载 作者:行者123 更新时间:2023-11-30 05:33:10 25 4
gpt4 key购买 nike

编程相当新,目前正在使用 FLTK 做一个项目,我想要一个 Fl_Int_Input,并使用它来创建一个 if 语句,该语句取决于人输入的内容,大致如下:

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

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

else{do this;}

但是当我使用'value'时,网上看似乎是在if语句中使用char值的方式,出现错误:ISO C++ forbids comparison between pointer and integer

我认为这是因为值是 const char* 而不是 char。代码在我使用时运行

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

但即使我输入 1 也没有任何反应

我应该如何使用此输入来创建 if 语句?

就像我说的,我对所有这一切都很陌生,所以我不知道您可能需要哪些其他相关信息来帮助我,我会尝试提供您可能需要的任何信息,这些是我的内容:

#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>

在这里输入代码,我注意到“1”变成了红色,这在我的代码中没有出现,也许这是相关的?

最佳答案

您需要了解 C 中字符串的工作原理。原因if(input->value()=="1")对你不起作用是因为 == char* 上的接线员values 进行指针比较,而不是字符串比较。

FL_Input::value() 返回指向为您的字符串分配的内存的指针但这与字符串文字 "1" 不同的内存位置,它存储在您程序的内存段中的某个位置。

要进行 C 风格的字符串比较,您可以这样做:

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

strcmp当您包含 <cstring> 时,该功能可用.

另一种方法(但不是很好)是将该值复制到临时 std::string对象并使用其重载 operator==( const char *) :

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

使用std::string , 包括 <string> .

更多阅读:

关于c++ - FLTK - 在 if 语句中使用输入值 (const char*),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34868125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com