question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
5,015,615
5,015,668
Memory leak on painting
I'm trying to create a simple game, but I can't find a certain memory leak. Every second or so, the program seems to use 3mb more memory. The problem is with this draw method. If I don't call this method, everything works fine. I'm trying to paint a sprite on several parts of the screen: void Map::draw(HDC hBackBufferD...
Are you using managed c++ or not ? You are allocating new Position (24*27) times. This lead to a 648 leaks each time you call Map::draw. Use an automatic object. void Map::draw(HDC hBackBufferDC) { for(int i = 0; i < 24; i++) { for(int j = 0; j < 27; j++) { if(mapState[i][j] =...
5,015,718
5,016,074
calling a C++ function from C# and sending data back to the C#
I have a C# application that calls functions in a DLL written in C++. The calls work fine and the code is executed using this method in the C#: [DllImport("myDLL.dll")] public static extern void Function(); static void Main() { Function(); } Now this works, I need the executing C++ code to send back the text to t...
Try using callbacks in C++ and sign them in C# C++ part typedef void (CALLBACK *pfNotifyMessage)(LPTSTR); extern "C" AFX_API_EXPORT void SetNotifyMessage(pfNotifyMessageType pfNotify); extern "C" AFX_API_EXPORT void Function(); In C++ Function call make call of pfNotifyMessage C# part public delegate void NotifyMess...
5,015,938
5,025,869
How to disable automatic creation SeriesCollection in Excel Chart
I have already this code Excel::_ApplicationPtr app("Excel.Application"); app->Visible[0] = false; Excel::_WorkbookPtr book = app->Workbooks->Add(); Excel::_WorksheetPtr sheet = book->Worksheets->Item[1]; RangePtr pRange = sheet->Cells; RangePtr pCell; pCell = pRange->Item[1][1]; // A1 pCell->Value2 = "1"; pCell = ...
Probably can't prevent it being created, but you can delete it immediately after creating the chart, then create you own series as required. In VBA: Set Chrt = wb.Charts.Add() Chrt.SeriesCollection(1).Delete
5,015,957
5,016,377
Problem with iostream,first write file in Binary mode then convert to and save ASCII
I am using iostream to collect data from a device.First I Write file in ASCII mode,it works well,but taking quite alot of time.Then I switsch to write in Binary mode and it is faster. float dist[41616]; ofstream d_ofs( "numbers.dat",ios::out |ios::app|ios::binary); // this is from the device API getting distance data...
You seem to be saving as float and reading as double. The read will (usually) be twice as large as the write so every double you read will actually be reading two of the written floats. You will get the wrong numbers because of this. try changing the double fnum[41616] to float fnum[41616] Also, its probably for t...
5,015,973
5,016,001
bool pointer member behaviour different on assigning true vs false
i use simple bool pointer class member. Assigning false resp. true behaves different - see comments in code. I outcomment one to test the other below. I use compiler call g++ -o basic basic.cpp class Test { public: int a; bool* abool; }; int main() { Test t; //t.abool = false; // WORKS...
That is because a conversion exists from false to 0. So it becomes t.abool = 0; which is initializing abool with NULL. However, true converts to 1 and since you can't initialize the pointer with an absolute integer, you get a compiler error. In the second case (with comment this should work IMO) you will get a seg faul...
5,016,076
5,016,254
C++ error enum and CRTP
template<class T> struct broker { typedef T typeBroker; static std::vector<std::string> extractListBroker(const std::string& broker) { std::vector<std::string> vec; if(broker.empty()) { for(int i=0;i<typeBroker::nbBroker;++i) vec.push_back( type...
You cannot use the derived type's internal types in the function declaration of the base, because the derived type's internal types aren't yet defined, the derived type is only declared. There are a number of ways to get around this, including type traits parameter and additional template parameter, and they are perfec...
5,016,095
5,016,103
basic_string expected initializer compile error
When i try to compile the following code: #include <string.h> using namespace std; typedef std::basic_string<char> foostring; foostring foo = "foo"; I get the following error: stringtest.cpp:5: error: expected initializer before ‘<’ token stringtest.cpp:6: error: ‘foostring’ does not name a type My compiler is: g++ (...
The header is <string>, not <string.h>. None of the standard library headers end with an extension. (You're including the C header string.h, which should be included in C++ via <cstring>, had that been what you actually wanted.)
5,016,117
5,018,714
good way to write "pointer to something" in C/C++
Is there a "good" way to write "pointer to something" in C/C++ ? I use to write void foo( char *str ); But sometimes I find it quite illogical because the type of str is "pointer to char", then it should more logical to attach the * to the type name. Is there a rule to write pointers ? char*str; char* str; char *str; c...
The common C convention is to write T *p, whereas the common C++ convention is to write T* p. Both parse as T (*p); the * is part of the declarator, not the type specifier. It's purely an accident of pointer declaration syntax that you can write it either way. C (and by extension, C++) declaration syntax is express...
5,016,195
5,016,305
Template operator << overloading and make_pair
I have some problems overloading operators with template members and using make_pair: class MyArchive { public: template <class C> MyArchive & operator<< (C & c) { return (*this); } }; class A { }; int main() { MyArchive oa; A a; oa << a; //it works oa << std::make_pair(std:...
The parameter of operator<< should be const : template <class C> MyArchive & operator<< (const C & c) Because std::make_pair returns a temporary object which cannot be bound to non-const parameter. But a temporary object can be bound to a const parameter, since then the life of the temporary extends, till the end of t...
5,016,262
5,016,421
Need to convert txt file into binary file in C++
I have a txt file with numbers like 541399.531 261032.266 16.660 (first line) 541400.288 261032.284 16.642 (2nd line)........hundred of points. i want to convert this file into binary format. Any one can help me?
In C++ just open the file for reading, then copy it to another file as a binary file. FILE *pTextFile, *pBinaryFile; char buffer; pTextFile = fopen("textfile.txt", "r"); pBinaryFile = fopen("binaryfile.bin", "wb"); while (!pTextFile(EOF)) { fread(buffer, 1, 1, pTextFile); fwrite(buffer, 1, 1, pBinaryFile); } fclose(p...
5,016,281
5,018,088
curllib POST body data (How to?)
Please show me how to make post of big text data with curllib? I want to make it not using parameters like &data="some big text", but using POST body; Thank you very much!!!
The simple case is just CURLOPT_POSTFIELDS: http://curl.haxx.se/libcurl/c/http-post.html If you want to send lots of data, perhaps use a CURLOPT_READFUNCTION callback: http://curl.haxx.se/libcurl/c/post-callback.html ... or if you're talking about doing a multipart formpost, you want CURLOPT_HTTPPOST: http://curl.haxx....
5,016,440
5,016,630
Can I code and compile all type of Visual Studio Application from Command line?
I am in the very first step of using Emacs as my programming environment. I run it in DOS Prompt using emacs -nw and do the development there. It's quite unbelievable, that I can do coding of J2EE and J2ME just using Emacs and its Eshell/Shell. And now about using it for Visual Studio development. Currently, I am work...
Lots of comments: There's no need for you to use -nw; Emacs works fine with windows. The analogue to build.xml is xxxxxx.sln, combined with the dependent project files, which are zzzzzzz.csproj. OF course replace xxxx and zzzzz with your solution and project names. you don't need the eshell or shell to compile. Yo...
5,016,464
5,016,479
Convert double to string using boost::lexical_cast in C++?
I' d like to use lexical_cast to convert a float to a string. Usually it works fine, but I have some problems with numbers without decimal. How can I fix number of decimal shown in the string? Example: double n=5; string number; number = boost::lexical_cast<string>(n); Result number is 5, I need number 5.00.
From the documentation for boost lexical_cast: For more involved conversions, such as where precision or formatting need tighter control than is offered by the default behavior of lexical_cast, the conventional stringstream approach is recommended. Where the conversions are numeric to numeric, numeric_cast may offer m...
5,016,622
5,016,679
Where does the k prefix for constants come from?
it's a pretty common practice that constants are prefixed with k (e.g. k_pi). But what does the k mean? Is it simply that c already meant char?
I haven't seen it that much, but maybe it comes from certain languages' (the germanic ones in particular) spelling of the word constant - konstant.
5,016,814
5,023,629
Should an exception in injected DLL crash the whole program?
I'm injecting a custom DLL into an x86 program. It's successfully injected, but when I cause an exception (like accessing a NULL pointer), it's detaching the DLL, without crashing the whole program. Is it how it should be? I want to crash the program actually. My OS is Windows 7.
What you are seeing may be the result of Windows 7's Program Compatibility Assistant. I don't think you can turn it off at the module level, if you know the target process, you can turn off at the process level.
5,017,001
5,017,022
like atoi but to float
Is there a function similar to atoi which converts a string to float instead of to integer?
atof() (or std::atof() talking C++ - thanks jons34yp)
5,017,060
5,017,102
Need help in reading .txt file which contains a table with blanks?
Consider this - "ID_REF" "GSM887" "GSM888" "GSM889" "GSM890" "GSM891" 10              -.427                          -3.841       .312 0 11              -.939           -1            -.024 Now how to recognize blanks when I am traversing through whole text file cont...
if the only delemiter is an arbitrary number of spaces, then you can't, because then "ID_REF" "GSM887" "GSM888" "GSM889" "GSM890" "GSM891" 11 -.939 -1 -.024 is the same as "ID_REF" "GSM887" "GSM888" "GSM889" "GSM890" "GSM891" 11 -.939 -1 -.024 check the character c...
5,017,099
5,017,177
Getting rid of #ifndef NDEBUG
Most of my classes have debug variables, and this makes them often look like this: class A { // stuff #ifndef NDEBUG int check = 0; #endif }; and methods might look like this: for (/* big loop */) { // code #ifndef NDEBUG check += x; #endif } assert(check == 100); Few things are uglier than all those...
How about: #ifndef NDEBUG #define DEBUG_VAR(T) static nullclass<T> #endif Now no additional storage is added to a class where DEBUG_VAR(T) is used as a member, but the declared identifier can still be used as though it were a member.
5,017,570
5,018,979
Term not evaluated to a function in C++
I have following code, which i taken from Boost and simplified for my project. Please accept my aplogies for pasting complete code, i done it so that it will be easy to answer my question. While compiling following code in VS 2008 i am getting followoing error. error C2064: term does not evaluate to a function taking 3...
The example code in the question compiles without errors with Visual 2008, gcc, Visual 2003 when we copy all in a single file. You have error C2064, it is probably because you either have a #define or another definition somewhere in other headers that you did not include in your sample, or that somehow you are not comp...
5,017,622
5,017,644
Generate executable file at runtime - C++ / Visual C++
Maybe you can help me with a question I have, related to C++ language: Is it possible or, is there a way to generate an executable file at runtime of a C++ Windows application? To illustrate you why I'm asking this, I will detail the scenario that I'm thinking right now: I have a C++ Windows Application that is more li...
Of course it is possible, the compiler itself is likely a program that fulfils this requirement. If you want to do it without just invoking a compiler though (and thus generate source code to feed it), you need to learn quite a bit about the machine language and executable file format of your platform.
5,017,629
5,017,695
How to use different overload of an inline function, depending on a compile time parameter?
I have a performance critical inline function, inline T func(T a, T b, int p). It can be optimized quite a bit, if p is known to be zero. However, I can't use an 'if' and penalize all the the other cases. What I want is to optimize the function only of I know at compile-time that p is zero. Is there a clean way to do t...
it's possible using templates. have a look at Boost enable_if, it has good explanation and usage examples
5,017,792
5,018,089
"undefined reference to" many (all?) of the functions in shared library (newbie)
I'm a novice at C++. Be patient if this is incoherent. I'm called upon to build a large system on linux that was originally built on OS X, where it works fine. The original authors are no longer with the company. The build system makes use of autotools, but there are also some hand made Makefiles which walk through...
This U ds_breakdown_from_time_interval tells me that ds_breakdown_from_time_interval will be resolved by another library during runtime. So I am guessing you need to link to the library that defines ds_breakdown_from_time_interval.
5,017,933
5,046,568
Extract still image from MJPEG file?
I need to modify each jpg-image of a mjpeg file. I have to use Visual Studio C++ 2010. So far, i need to a) load a mjpeg file from source and b) extract an bitmap (CImage, byte array, ...) In pseudo code it should look like: fun getBitmap(filename, timestamp) { MJPEG myInput = Open(filename); BITMAP myOutput = myIn...
Do you want to use the JPEG images in the video or would you decompress them anyway? An MJPEG stream consists of lots of JPEG images, without the usual JPEG header (and the code dictionaries). So if you want to extract them losslessly and get a lot of JPEG files in a directory, another tools may suit you better. Howeve...
5,017,943
5,018,122
How to run and debug C++ application in Eclipse that's started with a script?
I'm trying to use Eclipse CDT on Ubuntu for C++ development. I'm working on a large C++ project that leverages Tcl as a scripting language to kick off and control the application. How can I configure Eclipse to launch the application using shell scripts rather than using a C++ "main" application? The shell scripts laun...
Interesting question. Without being able to provide you a straight solution, but Eclipse (gdb) can be attached to a running program - that may not help in your case. What about trying to employ some kind of remote debugging? I.e. you start your program with gdb and configure gdb to wait for a remote debugger to attach...
5,017,979
5,018,074
Pointer to data that stored in a map container
I have 2 map one of them contain data for example struct DATA { int A1; int A2; }; typedef map<int,DATA> DataList; DataList myData; I have also tried some of the following: typedef map<int,DATA*??> DataListPointer; table<col_name,DataListPointer>; (Note: CC: I really do not get this line: map is a table....
This gets a pointer to a DATA value in the map, if present. DataList::iterator it = myData.find( 42 ); DATA * pData = NULL; if ( it != myData.end() ) { pData = &((*it).second); }
5,018,000
5,018,336
C++ Stack Fibinacci Hw Problem Clarification
Hey Guys. I need help understanding my hw assignment. I am starting out in C++ and don't know that much. I do know the basics of a stack and fibonacci sequence. However I do not exactly understand the problem given to me and need not the code to solving the problem but help clarifying some steps. Here's the hw: "By com...
Yes, it's calculating 5th fibonacci number (which happens to be 5, that's a bit confusing), but look at what you calculate when you call fibonacci(5), assuming the following code for fibonacci: int fibonacci(int n) { if (n <= 1) return n; else if (n == 2) return 1; else return fibonacci(n-1) + fibonacci(n-2...
5,018,092
5,018,137
Using DirectShow to capture frames and OpenCV to Process
I have made two different solutions for Video-to-Image Capturing and was wondering if I could intertwine the best of both worlds. I am currently using DirectShow to load in an AVI file and capture images. However, DirectShow's lack of image processing capabilities and the need to make additional filters have stopped ...
Yes, here is a link to an article: http://opencv.willowgarage.com/wiki/DirectShow
5,018,188
5,020,490
How to format a datetime to string using boost?
I want to format a date/time to a string using boost. Starting with the current date/time: ptime now = second_clock::universal_time(); and ending up with a wstring containing the date/time in this format: %Y%m%d_%H%M%S Can you show me the code to achieve this? Thanks.
For whatever it is worth, here is the function that I wrote to do this: #include "boost/date_time/posix_time/posix_time.hpp" #include <iostream> #include <sstream> std::wstring FormatTime(boost::posix_time::ptime now) { using namespace boost::posix_time; static std::locale loc(std::wcout.getloc(), ...
5,018,319
5,076,627
VS2008 C++ compiler keeps asking to build the project
Possible Duplicate: Visual studio keeps building everything I have a project that includes an idl file that generates a .c file that is included in another file of the same project. I build this project and all is fine, I then try to run the project and I am told the project is out of date and would I like to build ...
Once you've built the .idl file once, open it's properties and enable "Exclude from Build". If you update the file, you can build it manually by selecting the file in Solution Explorer and choosing "Compile" (the shortcut is Ctrl+F7 on my setup, but this may vary). If you don't include the generated files in your versi...
5,018,355
5,018,526
Load 2 versions of the same DLL in the same process
I want to do exactly what it is described here, but the accepted solution does not work for me. I suppose the reason is explained here : If a DLL with dependencies is loaded by specifying a full path, the system searches for the DLL's dependent DLLs as if they were loaded with just their module names. If a DLL...
Where have you embedded the manifest? The EXE or the DLLs? You have two basic ways of doing this, both involve turning "common" into a private SxS assembly by creating a manifest for it. Then: If DLL and DLL2 contain manifests listing dependent assemblies, then you need to add a dependentAssembly to their manifests sp...
5,018,603
5,018,794
a question about the precedence of C++ operators "address of" and "scope resolution"
Hello I have this code with a compiler error (error is from Microsoft Visual Studio 2008): class B { protected: int b; }; class A : public B { public: void foo() { &B::b; } // error C2248: 'B::b' : cannot access protected member declared in class 'B' }; while this code is error free: class B { protected: ...
In the first case you're taking the address of pointer-to-member B::b. Since such a pointer is NOT a member of the parent of A but a separate object, it can't access it via the protected mechanism. In the SECOND case where it works you're asking for the address of the specific instance of b, qualifying it with its base...
5,018,783
5,019,461
C++ pthread blocking queue deadlock (I think)
I am having a problem with pthreads where i think i am getting a deadlock. I have created a blocking queue which I thought was working, but after doing some more testing I have found that if i try and cancel multiple threads that are blocking on the blocking_queue, i seem to get a deadlock. The blocking queue is very s...
pthread_cancel() is best avoided. You can unblock all your threads blocked on Blocking_Queue::pull() by throwing an exception from there. One weak spot in the queue is that T t = _queue.front(); invokes the copy constructor of T that may throw an exception, rendering you queue mutex locked forever. Better use C++ scope...
5,018,908
5,123,482
Using VirtualQuery to find out which "file" uses certain page in memory
I'm using VirtualQuery to go through virtual space of my application. But I'd like to identify everything allocated by application, not just my exe - something like SysInternals' VMmap application - And I need to know which pages belong to which file (I need to identify pages allocated for my application and dlls). Ho...
You can use CreateToolhelp32Snapshot with TH32CS_SNAPMODULE to retrieve modules base addresses and sizes. For heap, you get use GetProcessHeaps() and HeapWalk() to get different heap regions (both committed and reserved). Other things (thread stacks, mapped memory) seem harder to retrieve.
5,018,971
5,034,030
debugging COM free registration (c++)
I've built a COM client application that uses two COM server dlls; I want this application to run without COM registration - ie: winsxs / .manifests I get a (...almost expected...) "Class not registered" message when I try to create an instance of my COM object from my client application. I've already succeeded that ki...
There are usually - at least - two manifests involved when building the activation context for registration free COM. There is the EXE manifest, that specifies its dependent assemblies, including the assembly containing the COM components, and there is the assembly manifest, describing the dll's, window classes, and CO...
5,018,973
5,020,556
How to achieve this specific datetime format using boost?
I want to format a datetime like this: YYYYMMDD_HHMMSS eg, 4 digit year, followed by 2 digit months, followed by 2 digit day, underscore, 24-hour hour, 2 digit minutes, 2 digit seconds. e.g.: 16th of February 2011, 8:05 am and 2 seconds would be: 20110216_080502 What format string should I use in the following code to ...
I believe you need to use wtime_facet, not time_facet. See the working program I posted on your other question.
5,019,046
5,019,133
reference to abstract class
What does it mean when there is a reference to an abstract class? I found it in code and I can't understand it. I thought that an abstract class can't be instantiated. How can you give it a reference?
A reference to an abstract class is just like a pointer to an abstract class: it needs to reference an object of some non-abstract subclass of the abstract class. You can use a reference like that to call virtual methods on the referenced class using the . syntax, in a way similar to a pointer to an interface in Java....
5,019,148
5,019,288
Doubt in STL priority_queue instantiation
In the code base I'm maintaining, I find the following instantiation of a STL priority_queue. I didn't understand the pq(order) part. What could be order there in the context of priority_queue instantiation? priority_queue<Record*, vector<Record*>, Comparator > pq(order); EDIT: Could order be the argument to the Compa...
From the looks of it, the code is using the following constructor of priority_queue: explicit priority_queue ( const Compare& x = Compare(), const Container& y = Container()); If so, then order is an instance of type Comparator. If it has been constructed with the default constructor, then you could just leave it ou...
5,019,393
5,019,424
Random number generator, C++
I know there is a bit of limitations for a random number generation in C++ (can be non-uniform). How can I generate a number from 1 to 14620? Thank you.
A common approach is to use std::rand() with a modulo: #include<cstdlib> #include<ctime> // ... std::srand(std::time(0)); // needed once per program run int r = std::rand() % 14620 + 1; However, as @tenfour mentions in his answer, the modulo operator can disrupt the uniformity of values std::rand() returns. This is ...
5,019,481
5,019,551
ClientClass does not name a type. GCC Linux
While making my code, i ran into a strange problem. I hold 1 file for all includes, lets call it includes.h and class files like clientclass.h etc. The problem is, when i try to compile my code i get a compiler error: /mnt/orange-new/units/includes.h|34|error: ‘ClientClass’ does not name a type| includes.h : #ifnde...
You have a circular dependency: includes.h -> clientclass.h -> includes.h. How this is resolved depends on which header gets included first, but it's always going to be confusing. Most likely it's causing the line #include <clientclass.h> to succeed but fail to include the content, since the include guard CLIENTCLASS_...
5,019,616
5,019,644
++i versus i++ : is there any difference on any modern compiler?
Possible Duplicate: Is there a performance difference between i++ and ++i in C++? I understand that: i++; Is supposed to take more instructions than ++i; Because it's generating an intermediate result that you don't need to use, so people put "++i" on lines of code that have no use for the intermediate result. H...
It does not matter when using it on an int. However, when using iterators or other objects that overload operator++, it might still make a difference.
5,019,775
5,060,773
C++: vector<string> *args = new vector<string>(); causes SIGABRT
Pretty self explanatory. Here's the method that's causing the SIGABRT on the 'new vector' line: vector<string> * Task::arguments() { vector<string> *args = new vector<string>(); // CAUSES SIGABRT int count = sizeof(_arguments); for (int x = 0; x < count; x++) { string argument(_arguments[x]); ...
The int count = sizeof(_arguments); seems pretty dubious. sizeof gives you size in bytes, not number of elements an array (except in the case where each element is exactly one byte, i.e. char). Cheers & hth.,
5,019,809
5,020,785
Dynamic link library does not generate a .lib file when compiled (Visual Studio C++ Express)
As part of learning C++, I wrote a simple class library + application that references it. Everything builds, except the class library does not generate a .lib file, which results in the application throwing a "LINK : fatal error LNK1104: cannot open file". This seems very reasonable; obviously, if a necessary file isn'...
Here is some sample code that demonstrates how to correctly export a class. Pay attention to the CONSOLETEST_EXPORT macro. This is the missing part of your solution. You need to define this macro in your DLL project, and leave it undefined in the projects that reference this dll. // MAIN.CPP - TestApplication #include...
5,019,856
5,019,896
Initialize static variables in C++ class?
I have noticed that some of my functions in a class are actually not accessing the object, so I made them static. Then the compiler told me that all variables they access must also be static – well, quite understandable so far. I have a bunch of string variables such as string RE_ANY = "([^\\n]*)"; string RE_ANY_RELUCT...
They can't be initialised inside the class, but they can be initialised outside the class, in a source file: // inside the class class Thing { static string RE_ANY; static string RE_ANY_RELUCTANT; }; // in the source file string Thing::RE_ANY = "([^\\n]*)"; string Thing::RE_ANY_RELUCTANT = "([^\\n]*?)"; Updat...
5,020,076
5,020,268
Passing a C++ complex array to C
I must pass complex data to a C function from C++. In C++ the data is naturally stored in a std::vector<std::complex> c. The C function expects the data as an array of double, double a[] such that a[0]=Re(c[0]), a[1]=Im(c[0]), a[2]=Re(c[1]), etc. What is the best safe way to pass such data? Is casting like (double*) (...
The C++0x standard went to lengths to guarantee that such conversions will work (§26.4): Moreover, if a is an expression of type cv std::complex<T>* and the expression a[i] is well-defined for an integer expression i, then: — reinterpret_cast<cv T*>(a)[2*i] shall designate the real part of a[i], and — reinterpret_cast...
5,020,084
5,020,116
Trying to use ofstream to write some basic text data
I'm just trying to write some text data out to a tab-delimited file. Here's the code. Name() and File() return CStringW, while ID() returns int, ofstream myfile(file); if (myfile.is_open()) { v::iterator i = begin(); while(i != end()) { myfile << i->Name() << L"\t" << i-ID() << L"\t" << i->File() ...
Use a wofstream, which has the appropriate operators for const wchar_t *. wchar_t * to ostream will use operator<<(ostream &, void *) as there's no operator for wchar_t * EDIT: Use .GetString() on the CStringW's.
5,020,203
5,020,285
QODBC3 Unable to bind to variable
I am attempting to add a new record to a table similar to the example listed below. When I run the query I get the following error: QODBC3: Unable to bind variable. What do I need to do to correct the error? QSqlQuery query; query.prepare("INSERT INTO Table (id, val, time) VALUES (:id, :val, :time)"); query.bindValue("...
I would guess it doesn't know how to bind the QTime object. Should you be using the toString method?
5,020,204
10,759,416
Loading a precompiled HLSL shader into memory for use with CreatePixelShader
I need to load a compiled pixel shader into memory to use with CreatePixelShader but I can't use any D3DX calls. How can I do this? (I'm using Visual Studio 2010 as my compiler and C++ as the language)
I realize someone posted pseudo-code earlier. Here is C++ code using the Windows SDK (and not the D3DX libraries as requested). Here "PixelShader.cso" is the precompiled hlsl shader generated by Visual Studio 11 from a .hlsl file in the project. The compiled .cso file is usually moved to the Projects/ProjectName/Debug ...
5,020,231
5,020,242
C++ Being told that there is a missing semicolon by compiler when trying to create a for loop
Why am I getting told that there is a missing ; when trying to create this for loop?
Replace for( count=1, count<=100, count++) with - for( count=1; count<=100; count++) for syntax: for ( init-expression ; cond-expression ; loop-expression ) statement
5,020,353
5,020,428
Some CPU Information
Well, i we're working on a CPU Controller, which shows all CPU Data. I've managed to get Windows Version, Windows Service Pack, Processor Name, Processor Speed, Processor Identifier(Though Registry Vals). But now i don't have any idea of how to get the processor Instructions, Caches, Video Card Information (Video Card ...
Take a look at: MEMORYSTATUSEX status; GlobalMemoryStatusEx(&status); For RAM and Virtual RAM For video memory vista: CreateDXGIFactory API via GetProcAddress() Below vista, d3d9 API GetAvailableTextureMemory()
5,020,423
5,020,438
How to add 0x00 at the end of a buffer
I have a piece of code as: char* buffer = new char[12]; memcpy(newbuffer, bytes, 10); //bytes is const void * Now I want the last 2 bytes which I have not used should be appended with 0000. How can I achieve that?
Easy as this: buffer[10]=buffer[11]=0; If it was a longer range you could have used memset or std::fill.
5,020,459
5,022,404
Deep copy of a QScriptValue as Global Object
I have a program using QtScript for some automation. I have added a bunch of C++ functions and classes to the global scope of the script engine so that scripts can access them, like so: QScriptValue fun = engine->newFunction( systemFunc ); engine->globalObject().setProperty( "system", fun ); I would like to be able to...
I got it working. Here's the solution in case it's useful for anyone else: QScriptValue copyObject( const QScriptValue& obj) { if( (obj.isObject() || obj.isArray()) && !obj.isFunction() ) { QScriptValue copy = obj.isArray() ? obj.engine()->newArray() : obj.engine()->newObject(); copy.setData( obj.da...
5,020,823
5,022,166
Listbox in main window
I'm creating a Win32 GUI application using Code::Blocks and MinGW. I am using this tutorial as a guide. Everything worked well until I decided I needed a listbox to display files in the current directory. I don't want the list box in a window by itself, I want it inside the main window. The tutorial I was following...
I assume you have a window procedure somewhere (let's call it WndProc) for your main window (let's call it hWndMain). Add a WM_CREATE handler in WndProc if it's not already there. In the WM_CREATE handler, add a call to CreateWindowEx to create the listbox as a child window of hWndMain: const HWND hWndList = CreateWind...
5,021,144
5,021,266
A Method that returns "const std::string&" with error checking
I am writing a function, which I want to return "const std::string&". Let's just look at the codes. class A { public: const std::string& GetString() const { if (list.empty()) { return "Warning!"; // how to get around this line. } return list[0]; }; protected: ...
if (list.empty()) { static std::string w("Warning!"); return w; } since you're returning a const reference, it does not matter that you're always returning a reference to the same object.
5,021,411
5,021,435
How to force GCC to put constants in memory instead of generating them?
I have a lot of constant arrays defined in several functions. Something like the following: const float values[4] = {-4312.435f, -432.44333f, 4.798, 7898.89}; After inspecting gcc assembler output I noticed that these constants are generated on each run of the functions. That's quite inefficient. I suspect that this...
Declare them with the static keyword. Edit: responding to your comment so I can show you some code: This is the expected behavior. Are you doing or seeing something different? $ cat foo.c++ int main(void) { static const float foos[] = {1.234f, 5.678f, 9.012f}; return 0; } $ g++ -S foo.c++ $ cat foo.s .fil...
5,021,774
5,021,823
Inherit from Base class with named constructors problems
class MeshGeneration{ public: static MeshGeneration CreateUnstrMesh() { cout<<"Unstr called"<<endl; return MeshGeneration(0);} static MeshGeneration CreateStrMesh() { cout<<"Str called!"<<endl; return MeshGeneration(1);} virtual void CreateHybridMesh(){}...
Two major problems: In order to use a polymorphic base class like you're attempting, you must use a reference, pointer, or smart pointer. Since the objects m1, m2, and m3 are plain variables of type MeshGeneration, they will never really be a DerivedMeshGeneration, no matter what the function to the right of the = ori...
5,021,848
5,215,731
How do I limit a function's callers to a particular logged-in user or role using WWSAPI?
I've been using http://blogs.msdn.com/b/haoxu/archive/2008/12/02/wwsapi-to-wcf-interop-nettcpbinding-with-transport-security.aspx as a guidelines on how to implement a secure connection using Windows Authentication. The next step for me is to use this to limit approved callers to either a login or a role/Windows group...
After further investigation this isn't possible with WWSAPI.
5,021,936
13,448,003
How to check if a parameter of an inline function is known at compile time?
I have a performance critical inline function. It generates some data, based on a parameter. I want the compiler to optimize the data generation for all invocations, where the parameter is known at compile-time. The problem is that I can't force the compiler to put the optimized data out of the stack to a static consta...
This is not portable, but on GCC and possibly Clang there is a __builtin_constant_p compiler function. This lets you ask the compiler if it knows the value of a variable during compile time. You can use it like this: void f(int arg) { if (__builtin_constant_p(arg) && arg == 0) { // Handle case where arg is 0 AND ...
5,022,031
5,022,084
How are STL List and Vector implemented?
How are STL List and Vector implement? I was just asked this in an an interview. I just said maybe by using binary tree or hash table about vector. not sure about list... Am I wrong, I guess so.. give some ideas thanks.
Hash table or binary tree? Why? std::vector, as the name itself suggests, is implemented with a normal dynamically-allocated array, that is reallocated when its capacity is exhausted (usually doubling its size or something like that). std::list instead is (usually1) implemented with a doubly-linked list. The binary tre...
5,022,334
5,022,434
How do I represent huge floating point numbers in Visual C++
double ld = 0.299999999999999990009; Gets truncated to 0.29999999999999999 How do I get more precision out of the float type? Is there a class that wraps a larger value?
The Gnu MP library apparently has support of arbitrary size floating point arithmetic. I'd recommend trying it out as GMP is one of the fastest general purpose arbitrary size arithmetic libraries out there. It's very stable, has comprehensive C interfaces, as well as C++ wrappers and binaries compiled for many compile...
5,022,374
5,023,086
include directories vs. lib directory concept question
What is the difference between linking to include files versus linking to lib files? I am fairly new to C/C++ and I'm having a hard time figuring out the difference between using include files and a static lib file to call functions. In my mind, the include files have functions that one can call just like .lib files.
In C++ (and C and other similar languages) a function is said to have both a declaration and a definition. The declaration is simply a short statement that declares that the function exists, and what its interface looks like. Consider a basic function add that adds two integers together. Its declaration might look like...
5,022,445
5,031,897
Can std::string overload "substr" for rvalue *this and steal resources?
It just occurred to me I noticed that std::string's substr operation could be much more efficient for rvalues when it could steal the allocated memory from *this. The Standard library of N3225 contains the following member function declaration of std::string basic_string substr(size_type pos = 0, size_type n = npos) c...
Firstly, an implementation cannot add an overload that steals the source, since that would be detectable: std::string s="some random string"; std::string s2=std::move(s).substr(5,5); assert(s=="some random string"); assert(s2=="rando"); The first assert would fail if the implementation stole the data from s, and the ...
5,022,590
5,022,680
Random memory accesses are expensive?
During optimizing my connect four game engine I reached a point where further improvements only can be minimal because much of the CPU-time is used by the instruction TableEntry te = mTable[idx + i] in the following code sample. TableEntry getTableEntry(unsigned __int64 lock) { int idx = (lock & 0xFFFFF) * BUCKETSI...
The point about copying the TableEntry is valid. But let’s look at this question: I suspect that accessing the memory randomly (…) could be expensive, but really that much? In a word, yes. Random memory access with an array of your size is a cache killer. It will generate lots of cache misses which can be up to three...
5,022,710
5,022,764
Determine type of argument
Is it somehow possible to reflect the type of the argument of a function at compile time? So that int b = add(3, 6) Would result in a template instantiation in the form of int add(int a, int b) { return a + b } out of some however declared function template A add(A a, B b) { return a + b } I don't know if that is po...
Templates do all their magic at compile time, but that seems to be quite adequate for what you're asking: template <class T> T add(T a, T b) { return a + b; } It does get a bit more complex when the two might not match, so (for example) you could add an int to a double and get a double result. The current standard do...
5,022,757
5,023,306
Ethernet Information
Well, i've looked on MSDN about this an only found this: GetAdaptersAddresses And what i'm trying to get is the Etherned Information, such as Description, Bytes Sent, Bytes Received, Bandwidth, Latency, etc. It's possible?
You can get most of that with GetIfTable2 and GetIfEntry2. If you need compatibility with XP and earlier, you'll want to look at GetIfTable and GetIfEntry instead. The *2 functions give more information, but only work on Vista and newer. I don't believe either will show latency though -- for that you pretty much need t...
5,022,763
5,022,944
Stack Overflow - Buffer Location in Memory
I'm researching buffer overflows (on IA32 architecture) and I would like to clarify one particular thing with this example program: int main(int argc, char **argv) { char array[512]; if(argc > 1) strcpy(array, argv[1]); } I followed the ebp,esp register change during execution of the assembly code: Dump of ass...
The compiler decided to allocate space for both the local variable and the parameters passed to strcpy() on the stack at the same time. sub esp,0x208 # 0x200 for array, 8 for 2 pointers ... mov DWORD PTR [esp+0x4],eax # argv[1], not push mov DWORD PTR [esp],eax # array So the array is act...
5,022,895
5,023,096
How to create COM object instance of a CLSID without knowing the IID
How can I create an instance of a class by its CLSID without knowing any of the interfaces it implements. For example the CLSID "{3ad05575-8857-4850-9277-11b85bdb8e09}" implements a class being derived from IFileOperation (in Windows 7), but if I didn't know that it derived from it, was there any way for create such ob...
David is right, you can always ask for IUnknown. But you'll hit the wall from there, COM does not provide a way to discover implemented interfaces beyond this if you don't know an IID. Given the possible number of GUID values, there's no practical way to 'try them all'. Nor does it make a lot of sense, if you'd gues...
5,023,038
5,023,578
Is there a way to get email of some user in the domain without usage of COM?
I found a way to get email address of some principal using ADsGetObject. However, it requires COM. My app doesn't use COM and I don't want to initialize it, just for the sake of doing one API call. Have you seen any Windows API which allow to get a user email?
Active Directory programming requires COM, there is no lower level API. Looking for alternatives: there is no great advantage to using C++ when dealing with something like email. It tends to work just as well from a scripting language, the bottleneck is not the language. Using ADSI from a scripting language (or espec...
5,023,137
5,023,495
Linking to static lib with managed components
After creating a GUI for my personal little application, I am trying to compile it as a static library to use in another project. The GUI is created and has other tasks performed with it through a managed public ref class that currently only has 5 functions, but will be added to. This is my header file in the static l...
A static .lib is not a valid target option for managed code. There is no implemented mechanism to get the all-important metadata associated with managed types the same kind of treatment as code. It cannot be carved up in bits in pieces and glued together again. The MSFT team probably considered it but got scared awa...
5,023,412
5,024,645
Visualize (directed) graphs with Qt
Are there widgets, libraries to visualize directed graphs of graphs in general with Qt? I want to build them in real time, while inspecting the JVM or is input/output with Graphviz the way to do?
Create a dot file and process it with graphviz. The syntax is so straightforward it should be trivial to output, if you can trivially traverse the graph.
5,023,454
5,024,031
how to differentiate auto getclipboarddata from real content pasting?
i'm trying to dev a simple tool which notify the user when he is pasting content into an unthorized application. I ve hooked the getclipboarddata function to do this. But application like MS office launch sometimes getclipboarddata to get retrieve the content but it s not a user pasting action. How to differentiate tho...
Any clipboard viewer is going to auto-paste data into itself. This includes clipboard programs like my own ClipMate, as well as Office, various editors with clipboard history, remote desktop, VMWare, and big-brother/malware apps. Assuming that you're talking about plain text, there is no way to determine a user-initia...
5,023,668
5,024,425
Creating and sending a crash report
Does anyone have any suggestions or tutorials for creating crash reports on a program? I want to start sending out a game I have been developing to people, but if the game crashes through error handling, I want to see those reports to an email address that I have registered (along with data collected from the program)....
IF you're using Visual Studio 2010 you can use the built in error reporting. You can then register with Microsoft, see http://msdn.microsoft.com/en-us/isv/bb190483
5,024,218
5,024,244
Why do I get a segmentation fault while iterating through this string?
I'm trying to implement a basic shift cipher in C++. I can't move forward until I figure out what's causing the segmentation fault. I stepped through the code using gdb and the problem seems to stem from the iterator. 1 #include <iostream> 2 #include <string> 3 4 std::string encrypt (std::string plain, int key); ...
You have declared encrypt as returning an std::string, but you don't return anything from the function. You need to return a value or you need to change the return type to be void to indicate that the function doesn't return anything. As for why it's crashing as written, I can only speculate. It is likely that the co...
5,024,445
5,024,652
need help with object oriented program in Visual C++
guys, I have the following code, but I'm getting error at compiling time... the error is at the end. Thanks 1st Class is "Person" #ifndef PERSON_H//protecting .h files #define PERSON_H//protecting .h files #include <iostream> #include <string> using namespace std; class Person { public: Person(); Person(string...
You haven't implement the default constructor Person(),you can write it like this: Person():weight(0) ,age(0){}; If you just want to complier it, this is enough; Here are some tips below: 1.Check your mind, does class Student really need a Person member. If you really need it, Student(Person) may add an explic...
5,024,864
5,024,947
Trying to implement HeapSort
I am getting stuck on heapSort. I have some code but I think its pretty wrong since I'm having hard time compiling it. Any suggestions? Heap sort should be fairly easy to implement but I have bunch of syntax errors. Here's my code: /* Framework for Heap Sort * CS333 Spring 2011 * */ #include <stdio.h> #define MAX_S...
Most of your problems seem to be in your HeapSort routine: void HeapSort(int data[]) { BuildMaxHeap(data); for (int j = sizeof(data); j > 0; j--) { When you pass an array to a function like this, what the function receives is actually a pointer. Using sizeof on that pointer will not tell you about the size of the ...
5,025,089
5,026,172
How to know which QLineEdit emitted the editingFinished() inside the signal handler?
I want to implement a custom response to user input for several similar QLineEdit objects. I want to create a common handler of editingFinished() or textChanged() signal and assign it to all the QLineEdits. However, the response requires the knowledge of the sender of the signal - for example, it must highlight the ent...
You can get pointer to sender with call to QObject::sender() and then cast this pointer to QLineEdit. Something like void MyClass::onTextChanged(const QString& text) { QLineEdit* edit = qobject_cast<QLineEdit*>(sender()); if (edit) { // Do something with QLineEdit } else { // Just to make sure that ...
5,025,110
5,025,353
Removing exe from windows startmenu quick launch
For work we have two shortcuts that get installed to the start menu with both of them pointing to the same exe (but the second with different command line arguments). Some times windows will pick the second shortcut to display in the start menu hot program list which is bad because it causes a full update of the appli...
Yes, in fact Raymond Chen just wrote about this: You can set the System.App­User­Model.Exclude­From­Show­In­New­Install property to VARIANT_TRUE to tell the Start menu, "I am not the primary entry point for the program; I'm a secondary shortcut, like a help file." Sample code (CCoInitialize class): #include <windows....
5,025,149
5,025,232
Make my desktop app appears to load/quit faster
I currently have a GUI single-threaded application in C++ and Qt. It takes a good 1 minute to load (read from disk) and ~5 seconds to close (saving settings, finalize connections, ...). What can I do to make my application appear to be faster? My first thought was to have a server component of the app that does all the...
The first step is to start profiling. Use an actual, low-overhead profiling tool (eg, on Linux, you could use oprofile), not guesswork. What is your app doing in that one minute it takes to start up? Can any of that work be deferred until later, or perhaps skipped entirely? For example, if you're loading, say, a list o...
5,025,260
5,025,771
Incrementing Preprocessor Macros
I'm trying to make a simple preprocessor loop. (I realize this is a horrible idea, but oh well.) // Preprocessor.h #ifndef PREPROCESSOR_LOOP_ITERATION #define MAX_LOOP_ITERATION 16 // This can be changed. #define PREPROCESSOR_LOOP_ITERATION 0 #endif #if (PREPROCESSOR_LOOP_ITERATION < MAX_LOOP_ITERATION) #define P...
The "problem" is that macros are lazily evaluated. Consider your macro definition: #define PREPROCESSOR_LOOP_ITERATION (PREPROCESSOR_LOOP_ITERATION + 1) This defines a macro named PREPROCESSOR_LOOP_ITERATION and its replacement list is the sequence of five preprocessing tokens (, PREPROCESSOR_LOOP_ITERATION, +, 1, an...
5,025,696
5,025,732
C/C++: "Grid[x + y * width]" versus "Grid[x][y]"
This is extremely specific and has almost no ramifications, but it has always managed to bother me just because I didn't know which would be generally better. I am hoping you fine folks will help me settle on one: Something ** grid; grid[x][y]; Something * grid; grid[x + y * width]; I know anyone who has programmed ...
Usually the second method is preferred, for a number of reasons: A single multiplication is marginally faster than an extra array-dereference Keeping the array contiguous also marginally increases speed, due to cache-hits In many cases, such as loading a bitmap file, or working work DirectX/OpenGL surfaces, it is nece...
5,025,843
5,025,909
Why do we have reinterpret_cast in C++ when two chained static_cast can do its job?
Say I want to cast A* to char* and vice-versa, we have two choices (I mean, many of us think we've two choices, because both seems to work! Hence the confusion!): struct A { int age; char name[128]; }; A a; char *buffer = static_cast<char*>(static_cast<void*>(&a)); //choice 1 char *buffer = reinterpret_cast<ch...
There are things that reinterpret_cast can do that no sequence of static_casts can do (all from C++03 5.2.10): A pointer can be explicitly converted to any integral type large enough to hold it. A value of integral type or enumeration type can be explicitly converted to a pointer. A pointer to a function can be explic...
5,026,104
5,026,192
how to store 1000000 digit integers in C++
in my problem i have to save big big integers like upto 1000000 digits and to do some operation. how can i do that.i know that a long int in c++ can store upto 10 digits
You can use GMP, the GNU arbitrary precision library. Just be aware that it's not a very good library if you run out of memory. By that, I mean it will just exit out from underneath you if it cannot allocate memory. I find this an ... interesting ... architectural decision for a general purpose library but it's popular...
5,026,119
5,026,279
How can I determine the type of a particular drive?
I feel somewhat noob yet with this of getting the Information of Hardware of the CPU, so i come with this request: Hard Drive, CD/DVD/Bluray reader, Floppy and if it's possible USB. I've been looking on MSDN GetDriveType but seems i'm bad at searching or i don't understand it. Any idea?
I'm not sure what you didn't understand about the documentation you linked to... The sole argument accepted by the function is the root directory of the drive you want to get information about (including a trailing backslash). The function returns a value indicating which type of drive that is. A chart is shown that gi...
5,026,224
5,026,241
Very odd conversion error
What, exactly, is a (*) and how do you cast it? "error C2440: '=' : cannot convert from 'char *[]' to 'char (*)[]'" Trying to get a SmartPointer to take array values. Header: template <typename T> class SmartPointer { private: T* myPtr; int* count; public: T* Value(); SmartPointer(const SmartPo...
I'm not familiar with this class but I would think you want: SmartPointer<char> str = SmartPointer<char>(new char[20]); Or possibly: SmartPointer<char> str = new char[20];
5,026,267
5,026,337
Performance of Graphviz
How fast is Graphiz? I want to implement a profiler which keeps track of threads state. I want to build and visualize waits-for graphs in real time (!). Is this even possible? Would Graphviz be the appropriate match? Otherwise, are there alternative for C++?
I would not use Graphviz because it is designed for creating graphical visualization of graph structures. Instead, might I suggest using the Boost Graph Library? While I have not used it personally, the Boost libraries are well respected, and it seems to be everywhere when I try to look for graphs in c++. I think that ...
5,026,429
5,056,571
Ignore mouse events over transparent parts of an svg image in qgraphicsview?
I am working on a graphics view (using C++ and Qt) which contains quite a few svg images. I intercept clicks on them, but i'd like not to receive events (or to be able to ignore them) when mouse is over transparent parts of svg items. Is it possible ? Should svg files be specifically designed for such use ? Is there so...
Having no other choice but to find out the hard way the answer to my question, here is what i did : looked for mousePressEvent definition in QGraphicsSvgItem.cpp. Found none. looked for mousePressEvent definition in QGraphicsItem.cpp (ancestor of QGraphicsSvgItem). The method exists but no relevant action could be f...
5,026,507
5,026,643
fill high data in wxListCtrl using wxThread- i can but
i want to fill database table in wxListCtrl, i can do this , i m using wxThread for this. my problem is - my concept is working for small amount of data, when i increase the size, it shows a error like- showingdatainwxlistctrl: ../../src/XlibInt.c:595: _XPrivSyncFunction: Assertion `dpy->synchandler == _XPrivSyncFuncti...
Instead of direct SetItem call from the worker thread, you need to post event to the main thread and add item in the event handler. Data for list control event should be placed to custom event class. See details in wxPostEvent function and here: http://wiki.wxwidgets.org/Custom_Events
5,026,561
5,026,576
Why might the following hang the program?
Now that I've got SmartPointers, I decided to try DumbPointers, which do the terribly difficult job of calling "delete" in a destructor. Deciding to continue my tests of storing arrays in SmartPointer, using a DumbPointer, I recalled a previous error and tried this: DumbPointer<char> dumbPointer = "Hello World\0"; ...
You must only delete pointers that you allocated with new. You pass a string constant to your DumbPointer, which has static allocation.
5,026,597
5,026,877
Python exception text on syntax errors (boost library)
I've got this code snnipet (the whole program compiles and links correctly): ... try { boost::python::exec_file( "myscript.py", // this file contains a syntax error my_main_namespace, my_local_namespace ); return true; } catch(const boost::python::error_already_set &) { P...
From the documentation of PyErr_Fetch: "The value and traceback object may be NULL even when the type object is not". You should check whether pvalue is NULL or not before trying to extract the value. std::string error; if(pvalue != NULL) { error = boost::python::extract<std::string>(pvalue); } If you want to chec...
5,026,655
5,026,663
struct forward declaration fails compile
I have the following code, but the compiler says sender_wrapper is undefined, even though I forward declared it. Can I not do a forward declare of a struct? (compiled with VS2003) struct send_wrapper; struct IPSend { IPSend::IPSend(const send_wrapper& sender) : _sender(sender) {} void IPSend::operator()(const...
Forward declarations of types can only be used to resolve declarations involving pointers and references to that type. Before the type has been fully defined, the compiler does not know anything about the type; e.g. what members it has, or how big it is. Therefore, you cannot use it as a by-value member of your struct...
5,026,735
5,026,949
Searching a C++ string and strip off text if present
I have to handle two types of string: // get application name is simple function which returns application name. // This can be debug version or non debug version. So return value for this // function can be for eg "MyApp" or "MyApp_debug". string appl = getApplicationName(); appl.append("Info.conf"); cout << "Outpu...
I would wrap getApplicationName() and call the wrapper instead: std::string getCanonicalApplicationName() { const std::string debug_suffix = "_debug"; std::string application_name = getApplicationName(); size_t found = application_name.find(debug_suffix); if (found != std::string::npos) { ap...
5,026,840
5,026,881
Attempting to write a String constructor to handle static char * such as "Hello World"
I've got a String class. Recently, I found the poor thing couldn't handle: String string = "Hello World"; I immediately decided to rectify this by adding a constructor. However, the exact parameter eludes me: inline String(const char[] str) : Array(str, sizeof(str) / sizeof(char)) { } generates the following ...
Simplest would be to take const char* as the parameter. Then use strlen to find the string length, then allocate len+1 characters using new and use strncpy to copy the string to the newly allocated memory. BTW, any specific reason not to use std::string?
5,026,972
5,027,360
Reflect a class' inheritance tree in C++?
Say I have the following classes in C++, and I want to inspect their inheritance: Vehicle Motorcar is a Vehicle Aircraft is a Vehicle Biplane is an Aircraft is a Vehicle Helicopter is an Aircraft is a Vehicle. I want to write a method getClassLineage() to do the following: Biplane b; cout << b.getClassLineage() << endl...
If you want a recursive-like approach you can do it with virtual functions and explicit scoped function calls: struct vehicle { virtual std::string lineage() const { return "vehicle"; } }; struct aircraft : vehicle { typedef vehicle base; virtual std::string lineage() const { return base::lineage() + "--aircra...
5,027,033
5,027,153
Obtaining an integer given its 4-byte unsigned integer little-endian form? (C++)
I'm probably very wrong here so please point out any misconceptions or mistakes I may have. The input for this assignment is a string of some characters followed by a series of 4-byte unsigned integers in little-endian form. I read the input into an STL string, and used the substring function to isolate just the intege...
If you got 0 for the 3rd byte, and your data matches your description, there's a bug in your code. The below code will correctly convert your sample data. // Data from file unsigned char Buffer[] = { 255, 255, 1, 0 }; // Convert the LSB data to an unsigned int unsigned int Result = 0; for (int i = 0; i < 4; ++i) { R...
5,027,178
5,027,203
How to implement menu Click events in windowproc?
I like to know which message is used to track the menu events.
Handle WM_COMMAND message. LOWORD(wParam) is menu ID.
5,027,190
5,027,688
initilizing a struct with input parameter
i am newbie at c++ and i have problem initializing my container occ_stat_t using the member function CNetwork::CNetwork. i guess that something is wrong at line: occ_stat[0]( num_elements_ ) , occ_stat[1]( num_elements_ ) but i dont really know how to write it correctly. i would like to learn how to initialize my struc...
I don't know if it is possible to access array subscripts in initializer lists. Unless on C++0x - which you are - but not in VS 2010 since it is not implemented there. So you've got to: CNetwork::CNetwork ( uint32_t num_elements_ ) { occ_stat[0].occupied_counter = boost::extents[num_elements_]; occ_stat[1].o...
5,027,216
5,027,276
Loop though all Drives?
Well, i've been working on a HDD Information (How can I determine the type of a particular drive? And well, everything works fine. But i don't know how to "check" or "loop" though all Drives (Hard Disks, USBs, CD/DVD/Bluray, Memory Card, etc) how do i loop though them? Since i don't want to do GetDeviceType for every l...
Well, you could call GetLogicalDrives(), which will give you a bitmask of used/unused drives: Return Value If the function succeeds, the return value is a bitmask representing the currently available disk drives. Bit position 0 (the least-significant bit) is drive A, bit position 1 is drive B, bit position 2 is drive ...
5,027,253
5,027,274
return a string in C++
I have a function in my C++ where I would like to return a string. I have tried a few ways but get errors. I've tried the C# way of return "...."; return myString; But get errors every time. EDIT: Unhandled exception at 0x100c1486 (DGGGGG.dll) in TestConsoleApp2.exe: 0xC0000005: Access violation writing location 0x7a0d...
std::string methodReturningString() { std::string something = "Hello "; something += "world!"; return something; }
5,027,456
5,027,507
Copying derived entities using only base class pointers, (without exhaustive testing!) - C++
Given a base class that is inherited by plethora of derived classes, and a program structure that requires you manage these via base class pointers to each entity. Is there a simple way to copy the entire derived object when only the base class pointer is known? Looking around it would seem possible (if incredibly tedi...
This approach is the preferred way of copying polymorphic objects because it offloads the responsibility of determining how to copy an object of an arbitrary type to that object, rather than trying to determine it at compile-time. More generally, if you don't know what the base class pointer points at at compile-time,...
5,027,500
5,100,426
How to solve this TabStop style Issue
I know that using isDialogMessage() function we can able to switch the focus from one control to another. My doubt is is it possible to override that the control should focus from first button to third button. If possible how to customize WS_TABSTOP property I also like to know that on what basis the focus is shifte...
Determine which control after which you want to insert the new control in the tab order then use SetWindowPos like this: SetWindowPos(hNewControl, hOldControl, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE); This changes the z-order of controls which, in turn, establishes the tab order.
5,027,840
5,027,904
Strange brackets in code I am reading
What does it mean if I have in the middle of c++ code, things in brackets likt: [..] What do these brackets mean? is it cli?
This is probably in your code editor and the purpose is to allow you to see more "context" code. Thus if you close a block of code you see more of what follows underneath.