VS2010 C++ math support (sin identifier not found) - c++-cli

I have a Windows Form on a new C++ project, a Button1, and inside the Button1 code am using some trig functions. I also have #include <cmath> in the resource.h file next to Form1.h file. (Below is the contents of resource.h):
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by app.rc
#include <cmath>
Why is the code not seeing the trig function?
The Button1 code is as follows:
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
double x[1000];
double y[1000];
double hifac;
double px[1000];
double py[1000];
int nout, jmax;
double prob;
int i,period;
period=300;
for (i=0; i<1000;i++){
x[i]=i;
y[i]=sin(2 * 3.14 * i / period);
}
}

Just put appropriate code in its appropriate place. That #include does not belong in resource.h, that header file should be reserved strictly for resource identifier definitions for unmanaged resources. Just about anywhere else is appropriate, obvious choices are source file where this code appears and the stdafx.h precompiled header file.
And use the appropriate math function. It is std::sin(), the missing namespace name is surely why you get the compiler complaint. But calling that function from managed code is inefficient, extra work is needed to run native code from managed code. It isn't much extra work but it is unnecessary work. Use Math::Sin() instead.

Related

Why doesn't Clion recognise WxPuts?

The wxPuts method used in this tutorial (http://zetcode.com/gui/wxwidgets/helperclasses/) doesn't work. Was it changed and the class is no longer available?
I tried searching online for some documentation about wxPuts and wxPrintf, but can't find anything relevant in the helper files in the wxWidg site.
#include <wx/textfile.h>
int main(int argc, char **argv)
{
wxTextFile file(wxT("test.c"));
file.Open();
wxPrintf(wxT("Number of lines: %d\n"), file.GetLineCount());
wxPrintf(wxT("First line: %s\n"), file.GetFirstLine().c_str());
wxPrintf(wxT("Last line: %s\n"), file.GetLastLine().c_str());
wxPuts(wxT("-------------------------------------"));
wxString s;
for ( s = file.GetFirstLine(); !file.Eof();
s = file.GetNextLine() )
{
wxPuts(s);
}
file.Close();
}
wxWidgets provides wrappers for all standard CRT functions working with strings in order to allow calling them with wxString or wchar_t (wide) strings. These wrappers are not documented because it doesn't make much sense to re-document the standard functions, but basically for any foo(const char* s) in the standard library, you have wxFoo(const wxString& s) declared in wx/crt.h header. You have to include this header to get these declarations, however.
Also note that most of wxWidgets functionality can't be used before the library is initialized.
TL;DR: you're missing #include <wx/crt.h>.

(C++ / CLI) Set contents of textbox to content of a .txt

I am looking to set the contents of a textbox to that of a .txt file,
however I cannot get it to work. I have a button which would "refresh" the
content of the textbox to that of the .txt file, here is the code I am using:
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
std::ifstream dat1("DataStore.txt");
String^ textHolder;
if (dat1.is_open())
{
while ( getline(dat1, line) )
{
textHolder += line.c_str;
}
textBox1->Text = textHolder;
dat1.close();
}
else textBox1->Text = "Unable to open file";
}
I get these 2 errors when compiling the program:
error C3867: 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>::c_str': function call missing argument list; use '&std::basic_string<char,std::char_traits<char>,std::allocator<char>>::c_str' to create a pointer to member
error C2297: '+=' : illegal, right operand has type 'const char *(__thiscall std::basic_string<char,std::char_traits<char>,std::allocator<char>>::* )(void) throw() const'
How do I make this work?
NOTE: I am trying to display the whole .txt file's contents in the textbox
If you are going to use C++/CLI you may as well take advantage of .net. You can use the File class to read the file for you:
System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
textBox1->Text = System::IO::File::ReadAllText("DataStore.txt");
}
You'll need to hope that the process working directory contains that file. In a GUI app you are better served by specifying full paths to files, since the working directory is typically ill-defined.
If you are trying to learn C++, then perhaps a .net C++/CLI WinForms application is not the place to start.
You forgot to end method c_str, change it to c_str()

Why is happened property write error?

c++ : Run time error is happened with error message like this:
RevStrings1->Height of reading included in error: The property is write-protected.
RevStrings1->Height の読み込中のエラー : プロパティは書き込み禁止です.
I'm using c++ builder 3.
This source code can be successfully compiled
setting library, include path and etc.
But run time error is happened.
I guess that this problem is about property read & write.
How can I simplly fix the problem ?
A variable RevStrings1 is created by a class TRevStrings.
//---------------------------------------------------------------------------
#ifndef RevStringsH
#define RevStringsH
//---------------------------------------------------------------------------
#include <SysUtils.hpp>
#include <Controls.hpp>
#include <Classes.hpp>
#include <Forms.hpp>
#include <Grids.hpp>
//---------------------------------------------------------------------------
class PACKAGE TRevStrings : public TStringGrid
{
private:
// void __fastcall SetWidth(int W);
// int __fastcall GetWidth(void);
// int FColCount ;
int FRowCount;
int FFixedCols ;
int FFixedRows ;
int FDefaultColWidth ;
int FDefaultRowHeight ;
int FHeight;
// int FWidth;
int FScrollBars;
int FMaxLength;
bool ColColors[24];
protected:
public:
__fastcall TRevStrings(TComponent* Owner);
void __fastcall DrawCellText(TRect ARect,int ALeft,String S);
virtual void __fastcall DrawCell(int ACol, int ARow,const Windows::TRect &ARect, TGridDrawState AState);
void __fastcall SetColor_Col(int Col,int Row);
void __fastcall SetColorFlag(int Col,bool flag);
bool __fastcall GetColorFlag(int Col);
void __fastcall SetEditText(int ACol, int ARow,const System::AnsiString Value);
void __fastcall Clear(bool ALLorONE,int Position);
void __fastcall DblClick(void);
__published:
// __property int ColCount = {read = FColCount};//FColCount};
__property int RowCount = {read=FRowCount};
__property int FixedCols = {read=FFixedCols};
__property int FixedRows = {read=FFixedRows};
__property int DefaultColWidth = {read=FDefaultColWidth};
__property int DefaultRowHeight = {read=FDefaultRowHeight};
__property int Height = {read=FHeight};
// __property int Width = {read=GetWidth,write=SetWidth};
__property int ScrollBars = {read=FScrollBars};
__property int MaxLength = {read=FMaxLength,write=FMaxLength};
/*
*/
};
//---------------------------------------------------------------------------
#endif
never heard of TRevStrings before
so it is either BCB 3 discontinued stuff (my BDS2006 does not have it at disposal) or you have some 3th party custom package installed but the header file suggest it is based on TStringGrid so if below text does not work for it then you can switch to TStringGrid instead.
in TStringGrid
size properties are accessible normaly:
StringGrid1->Height=256;
StringGrid1->Width=128;
if you want to have size-able col/rows then do not forget to open Options property and set goRowSizing,goColSizing to true and starting sizes are DefaultColWidth,DefaultRowHeight. Here example of usage
// resize the grid
StringGrid1->Height=128;
StringGrid1->Width=256;
// access to Cell AnsiStings
StringGrid1->Cells[0][0]="(0,0)";
StringGrid1->Cells[1][1]="(1,1)";
StringGrid1->Cells[1][2]="(1,2)";
StringGrid1->Cells[2][1]="(2,1)";
// resizing row/col
StringGrid1->RowHeights[0]=15;
StringGrid1->RowHeights[1]=20;
StringGrid1->ColWidths[0]=20;
StringGrid1->ColWidths[1]=15;
As your class is derived from this so this should work also for it if not the there are more possibilities:
you have unrelated bug somewhere
overwriting what you should not damaging the C++ engine your App is running on or have memory leak somewhere or your memory manager is invalidated see
bds 2006 C hidden memory manager conflicts
but that is probably not the case or you are calling VCL/Winapi visual stuff from threads.
To check for all this:
create empty application, add your TRevString and try to set its height on runtime. If no error occurs you have a bug somewhere if error occurs then:
this component is not able to resize on runtime this way
try to use functions like SetSize,SetBounds instead or place the component on some panel align to Client and resize panel
if even this does not help switch to standard TStringGrid
you can also try to cast you RevString to StringGrid first
((TStringGrid*)(RevString1))->Height=25;
Borland compilers sometimes get weird
few times (around 10) over the years I use BCB/BDS the compiler sometimes compile wrongly. The app is running but some code gets distorted or discarted so what helps?
close IDE or even restart Windows
delete all map,obj,tds temp files prior to compiling rebuilding
sometimes is needed that you add empty line of code or swap 2 lines of code
Identifiers/Names collisions
if you name your stuff in similar way to VCL functions then you ask for problems usual error is to name function Draw() ... (use draw() instead and you are fine)
for big projects
if you add your source code as new unit to project instead of just include it (it is present in Object Manager) then in big projects you will got big problems. It looks like units are compiled differently then normal included files in units are expected Formulars and other VCL stuff components so if you got your own non visual classes as units they sometimes stop working as expected creating weird behavior (even your error could be caused by it).
I observe this on BCB5 and BDS2006. In BCB3,BCB4 I did not make big enough projects to spot this and BCB6 is so buggy so its unusable with big projects anyway. By big projects I mean > 1 MB of pure C++ code
The error is self-explanatory - the Height property of the RevStrings1 object is not allowing its value to be assigned. This is evident by looking at the declaration of the Height property in the TRevStrings class:
__property int Height = {read=FHeight};
TRevStrings is going out of its way to make the Height property read-only, overriding the native read-write Height property that is inherited from TControl:
__property int Height = {read=FHeight, write=SetHeight, nodefault};
This is odd for TRevString to do, as it is a visual component that needs to be sizable. Unless it requires a specific height that the user cannot change (in which case declaring the Height property as read-only is not the correct way to handle that - the component should override the virtual SetBounds() method instead and just ignore any new Height value being assigned).
That being said, the reason you see the error at run-time is because the IDE is storing the design-time Height value of the RevStrings1 object in the parent Form's DFM resource at compile-time. That is why you are not finding any RevStrings1->Height in your code - it is coming from the Form Designer instead. The TRevStrings class is not overriding DFM behavior for the Height property, so when the VCL's DFM streaming system parses the Form's DFM resource at run-time, it sees the stored Height value and detects that the object's Height property is actually read-only, and so throws an exception to cancel DFM streaming (and thus the Form's construction).
This is a bug in the TRevStrings implementation. At the very least, if the author had wanted to prevent the Height from being streamed (thus preventing the run-time error), the Height property should have been declared like this instead:
__property Height = {read=FHeight, stored=false};
On a side note, most of the TRevStrings data members (FColCount, FRowCount, FFixedCols, FFixedRows, etc) should never have been declared at all, but instead should have been inherited from the base TStringGrid class.
Whoever wrote this component clearly did not know what they were doing.

Add Forms from another project in Borland C++

I'm currently working on a project using Borland C++, I have two Forms so far but each one in an independent Project, I wish to join these two project into one project so I can switch between the Forms.
I want to have only one executable file (for security purposes), I tried reading some pdfs about borland c++, also tried googling it, but no luck.
if there's a way to do so, I wish you could guide me or give me some hints.
Note: I'm using Borland C++ Builder 6, under Windows 8.1.
I am used to BDS2006 so for newer IDE/Compilers it can be different
1.form copy
has .h,.cpp,*.dfm files
copy them to target project directory
2.open target project in IDE
3.add forms to project
find add to project in IDE main menu (I think it is in Project tag)
then select *.dfm files of your new forms click add or OK ...
4.Open target project source code (*.cpp)
should look like this:
//$$---- EXE CPP ----
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
//---------------------------------------------------------------------------
//*** here you have line for each form type and its name in forms menu
USEFORM("win_view.cpp", win_view);
USEFORM("win_main.cpp", win_main);
USEFORM("win_editor\win_editor_setup.cpp", win_EditorSetup);
USEFORM("win_editor\win_editor.cpp", win_editor);
USEFORM("win_editor\win_editor_find.cpp", win_EditorFind);
//---------------------------------------------------------------------------
WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
try
{
Application->Initialize();
//*** here create form for each static form you want
//*** dynamic windows (created in runtime are not here !!!
Application->CreateForm(__classid(Twin_main), &win_main);
//*** here load cross references to forms if needed
Application->Run();
}
catch (Exception &exception)
{
Application->ShowException(&exception);
}
catch (...)
{
try
{
throw Exception("");
}
catch (Exception &exception)
{
Application->ShowException(&exception);
}
}
return 0;
}
//---------------------------------------------------------------------------
5.dynamic forms
add #include of *.h for all dynamic/used inside form files to main form cpp file
this makes them accessible from main form
now you can crete / destroy windows
should look like this:
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "win_main.h"
//*** add the dynamic/used forms *.h files
#include "win_view.h"
#include "win_editor\win_editor.h"
//---------------------------------------------------------------------------
//*** add pointer to dynamic forms
Twin_view *win_view=NULL;
//---------------------------------------------------------------------------
void __fastcall Twin_main::some_event(...)
{
win_view=new Twin_view(win_main);
if (win_view)
{
win_view->OnResize(win_view);
win_view->_can_close=false;
}
}
//---------------------------------------------------------------------------
void __fastcall Twin_main::FormDestroy(TObject *Sender)
{
//*** destroy form before exiting also can call ->Close() and wait few [ms] before
if (win_view) { delete win_view; win_view=NULL; }
}
//-------------------------------------------------------------------
you can also move the form pointers to owner form class to make it more objective c++ like
and allow to make multiple originaly main forms in future (in another project later)
6.static used forms
just include *.cpp file instead of *.h
the pointer to these forms are directly in *.cpp files (at the start)
[notes]
if your forms have some global variables
then you can not use more then 1 form of that type
also the global variable names have to be different between used forms
do not change namespace for them it will make VCL crazy

How do I pass QMainWindow resize events down to a QGLWidget contained in the QMainWindow?

Initially, I followed the structure of http://qt-project.org/wiki/How_to_use_OpenGL_Core_Profile_with_Qt. I created a vanilla Visual Studio 2010 Qt application project, clicked on the .ui file to start Qt Designer, inserted a QWidget and promoted it to myglwidget. I then created a myglwidget subclass of QGLWidget.
That worked fine, and I got my red triangle.
The issue is that myglwidget doesn't get any of the resize events when the main window is resized, even if I set the widget size properties to "expanding."
And when I restructure my app constructor to call setCentralWidget(&myglwidget_) the code compiles and runs but no OpenGL window appears.
I'm not seeing how to resize my widget to match the main window size. I'm also not understanding why the setCentralWidget approach didn't work.
I believe I know how to solve the problem by writing explicit Qt code, but that defeats the purpose of my trying to build an OpenGL app in Qt using Qt Designer.
The following code for the application "baz6" fixes the problem. The code I inserted in the wizard-generated code is flagged with //***
baz6.h:
#ifndef BAZ6_H
#define BAZ6_H
#include <QtGui/QMainWindow>
#include "ui_baz6.h"
#include "myglwidget.h" //***
#include <QResizeEvent>
class baz6 : public QMainWindow
{
Q_OBJECT
public:
baz6(QWidget *parent = 0, Qt::WFlags flags = 0);
~baz6();
private:
Ui::baz6Class ui;
myGLWidget *myglwidget_; //***
};
#endif // BAZ6_H
baz6.c:
#include "baz6.h"
#include "myglwidget.h"
baz6::baz6(QWidget *parent, Qt::WFlags flags)
: QMainWindow(parent, flags)
{
ui.setupUi(this);
myglwidget_ = new myGLWidget(); //***
setCentralWidget(myglwidget_); //***
}
baz6::~baz6()
{
}
Previously, I had not explicitly constructed the myGLWidget.