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
2,051,462
2,051,489
Question About Why String is Truncated on First Instance of \0
I have a function which reads in a character, one byte at a time, through the serial port. After these bytes are collected, they are passed to a method to process the bytes and message. I know how to fix the problem (fix is below), but why do my bytes get truncated when I don't perform the fix? unsigned char dpBuf[255...
buff is declared as const char*, so sizeof(buff) returns the size of such a pointer, which seems to be 4 bytes on your machine. Therefore the first four bytes of the buffer are then printed in the loop. It doesn't matter that dpBuf is declared as an array of larger size because it is passed to the function as a pointer...
2,051,534
2,051,585
Floating Point Math Execution Time
What accounts for the added execution time of the first data set? The assembly instructions are the same. With DN_FLUSH flag not on, the first data set takes 63 milliseconds, the second set takes 15 milliseconds. With DN_FLUSH flag on, the first data set takes 15 milliseconds, the second set takes ~0 milliseconds. T...
Quoting from Intel's optimization manual: When an input operand for a SIMD floating-point instruction [here this includes scalar arithmetic done using SSE] contains values that are less than the representable range of the data type, a denormal exception occurs. This causes a significant performance penalty...
2,051,685
2,051,814
Review: reusable safe_bool implementation
Trying to find a "simple to use" safe_bool idiom/implementation, I've ended up with my own. Q: Is this implementation correct? template <typename T> class safe_bool { protected: typedef void (safe_bool::*bool_type)() const; bool_type to_bool_type(bool b) const { return b ? &safe_bool<T>::safe_bool_true :...
Using a pointer to a member function as the bool alias is idiomatic, as you're doing here. Your implementation looks correct for what is there, but slightly incomplete. See http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Safe_bool IMO safe_bool falls into the category of things which do more harm than good; ie the com...
2,051,705
2,880,215
Has anyone used Facebook Scribe? (the tool for logging everything)
How does it work? (Explain it in terms of server, writes, GETs, values, whatever). DOes it work with Win32 apps?
I'll try to explain: There is an application, with thrift class/interface. When event that you want to log occures, you send message to the Server, which collect logs from many sources (application, server logs, etc) And then server decides what do do with it: generate visualization, send over tcp/ip, store i...
2,052,224
2,052,254
Virtual destructor for boost:noncopyable classes?
I have a question about the following code: class MyClass : private boost::noncopyable { public: MyClass() {} virtual ~MyClass() {} } class OtherClass : private boost::noncopyable { private: MyClass* m_pMyClass; } My thoughts are that MyClass cannot be copied using construction or assignment. Us...
No, the entire point of a virtual destructor is so derived classes can properly destruct polymorphically. If this will never be a base class, you don't need it to be virtual.
2,052,497
2,052,555
Is there any way to have dot (.) match newline in C++ TR1 Regular Expressions?
I couldn't find anything regarding this on http://msdn.microsoft.com/en-us/library/bb982727.aspx. Maybe I could use '[^]+' to match everything but that seems like a hack?
Boost.Regex has a mod_s flag to make the dot match newlines, but it's not part of the TR1 regex standard. (and not available as a Microsoft extension either, as far as I can see) As a workaround, you could use [\s\S] (which means match any whitespace or any non-whitespace).
2,053,029
2,053,078
How exactly does __attribute__((constructor)) work?
It seems pretty clear that it is supposed to set things up. When exactly does it run? Why are there two parentheses? Is __attribute__ a function? A macro? Syntax? Does this work in C? C++? Does the function it works with need to be static? When does __attribute__((destructor)) run? Example in Objective-C: __attribute...
It runs when a shared library is loaded, typically during program startup. That's how all GCC attributes are; presumably to distinguish them from function calls. GCC-specific syntax. Yes, this works in C and C++. No, the function does not need to be static. The destructor runs when the shared library is unloaded, typi...
2,053,106
2,053,205
initialize boost::multi_array in a class
For start I would like to say that I am newbie. I am trying to initialized boost:multi_array inside my class. I know how to create a boost:multi_array: boost::multi_array<int,1> foo ( boost::extents[1000] ); but as part of a class I have problems: class Influx { public: Influx ( uint32_t num_elements ); bo...
Use an initialisation list (BTW, I know zip about this bit of Boost, so I'm going by your code): Influx::Influx ( uint32_t num_elements ) : foo( boost::extents[ num_elements ] ) { }
2,053,798
2,053,826
Extending Ruby with C++?
Is there any way to pass Ruby objects to a C++ application ? I have never done that kind of thing before and was wondering if that would be possible. Would it require to modify the Ruby core code ?
Yes, and no, respectively. Ruby is written in C. C++ is, by design, C-compatible. All objects in Ruby are held by a VALUE object (which is a union type), which can be passed around quite easily. Any directions you find for extending Ruby with C apply in C++ with little modification. Alternatively, you can use something...
2,054,427
2,054,456
VC ++ express, how do I fix this error?
I have experience programming in C#, but I'm taking a C++ class this semester, and I'm writing my second project, but I keep getting this error when I try to build a debug configuration of my program. My build log is below, any ideas on what's going on? I'm at a loss. Thanks everyone! 1>------ Rebuild All started: Proj...
You should look at the buildlog.htm file that is given in the build output. It will give you more (useful) information about what has happened.
2,054,477
2,054,546
Why is my C++ app faster than my C app (using the same library) on a Core i7
I have a library written in C and I have 2 applications written in C++ and C. This library is a communication library, so one of the API calls looks like this: int source_send( source_t* source, const char* data ); In the C app the code does something like this: source_t* source = source_create(); for( int i = 0; i <...
From examining your source code alone, I can't see any reason why the C++ code should be faster. The next thing I would do is check out the assembly code that is being generated. If you are using a GNU toolchain, you have a couple of ways to do that. You can ask gcc and g++ to output the assembly code via the -S comma...
2,054,572
2,054,602
Linker options for Boost
I'm wondering if there are any simple ways to link boost libraries (all or individual) via some entry like.... -lSDL_ttf The above links SDL's True Type Font library. Can this be done with boost? If so, I'm not sure what file I'm linking for to link. I'm currently using boost_1_40_0. If this isn't possible, or there a...
Most boost libraries don't need to be linked as they are header only. For those that are not header only, see the instructions here on the naming conventions and make sure you put the folder containing the boost libraries in your library search path if you want to avoid specifying it explicitly.
2,054,710
2,054,745
Can a C++ class determine whether it's on the stack or heap?
I have class Foo { .... } Is there a way for Foo to be able to separate out: function blah() { Foo foo; // on the stack } and function blah() { Foo foo* = new Foo(); // on the heap } I want Foo to be able to do different things depending on whether it's allocated on the Stack or the Heap. Edit: Alof of people h...
You need to actually ask us the real question(a) :-) It may be apparent to you why you think this is necessary but it almost certainly isn't. In fact, it's almost always a bad idea. In other words, why do you think you need to do this? I usually find it's because developers want to delete or not delete the object based...
2,055,205
2,055,242
There is an if-else, is there a Neither Nor statement?
Is there a neither A nor B syntax?
While there isn't a built-in syntax to do this, I'd suggest you take a look at the list of supported logical operators and then carefully study De Morgan's laws. Sufficient knowledge in these two fields will allow you to write any logical statement in if–else if syntax. EDIT: To completely answer your question (althoug...
2,055,221
2,788,610
How to build "Auto Detect Proxy Settings" In Windows and in Mac
What are the steps to implement that feature in 1) Windows and 2) in Mac? I went through these, still I am not very clear! I am using C/C++ in Windows and in Mac. So, Win API or Mac API will be enough. I am also confused because Mac Firefox has also has a option "Use system proxy settings", which is not present in Wind...
I using librproxy. That solved this requirement.
2,055,350
2,055,373
Any cross platform way to build cpp skeleton from a header?
I'm tired of copy pasting the header into my cpp file then hacking at it until its in the correct form. Has anyone made a program to read a header file and make a corresponding cpp skeleton? I need something that is cross platform or bare minimum works on Linux. A vim plugin would also be acceptable. Example class A { ...
http://www.vim.org/scripts/script.php?script_id=2624
2,055,486
2,055,501
Why can't I access a public var using the getter?
having a file containing these statements: public: boost::shared_ptr<TBFControl::TbfCmdHandler> _tbfCmdHandlerPtr; // will be private later... boost::shared_ptr<TBFControl::TbfCmdHandler> getTBFCmdHandler() { return _tbfCmdHandlerPtr; } I can use it this way: boost::shared_ptr<TBFControl::TbfCmdHandler>myTbfCmdHandle...
Obviously, this->getTBFInstallation() returns a const pointer. You need to make the function getTBFCmdHandler const as well. boost::shared_ptr<TBFControl::TbfCmdHandler> getTBFCmdHandler() const { return _tbfCmdHandlerPtr; } Note the const keyword at the end of the first line. Edit: By adding const, you're in eff...
2,055,518
2,055,645
Converting: #define xxxxxx ((LPCSTR) 4)
In WinCrypt.h I see: #define CERT_CHAIN_POLICY_SSL ((LPCSTR) 4) WINCRYPT32API BOOL WINAPI CertVerifyCertificateChainPolicy( IN LPCSTR pszPolicyOID, IN PCCERT_CHAIN_CONTEXT pChainContext, IN PCERT_CHAIN_POLICY_PARA pPolicyPara, IN OUT PCERT_CHAIN_POLICY_STATUS pPolicyStatus ); The first argument ...
Sometimes an API will take a parameter that can be a 'cookie' or ID for a well-known object or a pointer to a name (for example),which is what appears to be the case here. 4 is a cookie/handle/ID for the well-known CERT_CHAIN_POLICY_SSL policy. Some users of the API might specify a policy that's not known to the lib...
2,055,818
2,055,884
Why is Visual C++ 2010 complaining about 'Using uninitialized memory'?
I've got a function that takes a pointer to a buffer, and the size of that buffer (via a pointer). If the buffer's not big enough, it returns an error value and sets the required length in the out-param: // FillBuffer is defined in another compilation unit (OBJ file). // Whole program optimization is off. int FillBuffe...
This has to be a bug in Visual Studio 2010. Wrapping malloc removes the warning, as in the following tested code: char * mymalloc(int i) { return (char *) malloc(i); } // ... void *r = mymalloc(cb); char *p; p = (char *) malloc(cb);
2,055,871
2,055,906
Inline assembly inside loops
I use inline assembly massively in a project where I need to call functions with an unknown number of arguments at compile time and while I manage myself to get it to work, sometimes, in linux (in windows I don't recall having that problem) strange things like this happen: If I have something like for(int i = 1; i >= 0...
I can't understand what's the problem but try to write code using clear asm code same as asm{ loop1: mov ax, this->var ... dec ax cmp ax, 0 je exit jmp loop1 } ... exit: Also try to make "var" value as static may it help too.
2,056,033
2,064,969
Netbeans C/C++ JavaDoc code-completion
I am developing C++ in NetBeans 6.7.1. When I press CTRL + space for autocomplete there is shown only method's signature. I am using JavaDoc for commenting my code but NetBeans doesn't show it. I have installed Doxygen plugin but it is only for generating complete documentation. Is there any way how to force the IDE to...
So I asked on NetBeans forum this question ( using friend's account because I don't have my own ) and there is the conclusion: It is impossible and it is in requests.
2,056,380
2,056,425
Linking error: Undefined Symbols, lots of them (cpp cross compiling)
I get to the very last linking command (the actual executable is being linked) but i get a BUNCH of undefined symbols (and they're in cpp and look so scary to me, a simple c programmer) --its probably something simple but i cant get what im supposed to put as linker (its using gcc here...? is that appropriate? g++ told...
Seems you are trying to link C++ code with a C (gcc) linker call. That'll not include the appropriate libraries which is just what you are seeing. Try g++ instead of gcc (or throw out the C++ code/libraries).
2,056,778
2,058,296
How to display a modal message box in C++ on Mac?
CFUserNotificationDisplayAlert and CFUserNotificationDisplayNotice creates a non-modal window and this is bad because it could bring your application UI in a very undesired state if you select the original application window (the message box is hidden but the applicaton does not respond). The old SystemAlert was modal ...
It looks that CreateStandardAlert is the right solution because this one is modal. DialogRef theItem; DialogItemIndex itemIndex; CreateStandardAlert(kAlertNoteAlert, CFSTR("aaa"), CFSTR("bbb"), NULL, &theItem); RunStandardAlert(theItem, NULL, &itemIndex);
2,056,996
2,057,044
Comparison is always false due to limited range ... with templates
I have a templated function that operates on a template-type variable, and if the value is less than 0, sets it to 0. This works fine, but when my templated type is unsigned, I get a warning about how the comparison is always false. This obviously makes sense, but since its templated, I'd like it to be generic for al...
#include <algorithm> template<class T> T& trim(T& val) { val = std::max(T(0), val); return val; } It's not apparent from the question that passing by non-const reference is appropriate. You can change the above return nothing (void), pass by value and return by value, or pass by const& and return by value: templa...
2,057,047
2,057,067
Freeing a Pointer if memory isn't being referenced by anything else
I have a method that has a few pointers as parameters. This method can be called with either named pointers from the callee or dynamically create a pointer to a new object and pass it in as an argument directly as the method is being called. myClass *myPtr = new myClass(...); myMethod(myPtr); Verus myMethod(new myCla...
I would say, in this case caller should be responsible for freeing the object. You can consider various options, simplest is: myClass myInstance = myClass; // or myClass(arg1, arg2, ...) // and the pass it to your method like this: myMethod(&myInstance); You could also consider some smart pointer options like std::tr...
2,057,350
2,057,392
Determine input encoding by examining the input bytes
I'm getting console input from the user and want to encode it to UTF-8. My understanding is C++ does not have a standard encoding for input streams, and that it instead depends on the compiler, the runtime environment, localization, and what not. How can I determine the input encoding by examining the bytes of the inp...
In general, you can't. If I shoot a stream of randomly generated bytes at your app how can it determine their "encoding"? You simply have to specify that your application accepts certain encodings, or make an assumption that what the OS hands you will be suitably encoded.
2,057,424
2,057,464
LRU implementation in production code
I have some C++ code where I need to implement cache replacement using LRU technique. So far I know two methods to implement LRU cache replacement: Using timeStamp for each time the cached data is accessed and finally comparing the timeStamps at time of replacement. Using a stack of cached items and moving them to t...
Recently I implemented a LRU cache using a linked list spread over a hash map. /// Typedef for URL/Entry pair typedef std::pair< std::string, Entry > EntryPair; /// Typedef for Cache list typedef std::list< EntryPair > CacheList; /// Typedef for URL-indexed map into the CacheList typedef boos...
2,057,456
3,984,857
OpenGL ES 2.0 SDK for Windows Mobile
I would like to get started developing native (C/C++) OpenGL ES 2.0 applications for Windows Mobile (version 5 or later, any version would do, really). I do however have trouble finding appropriate headers and libraries. What I am looking for is a OpenGL ES 2.0 SDK for Windows Mobile, or an SDK which contains the appro...
It would seem there is no such SDK. Not publicly available anyhow. From what I gather, developers that have created GLES-applications for Windows Mobile has used the strategy suggested by Virne in one of the comments and created a lib from the GLES DLL.
2,057,523
2,057,702
String reference not updating in function call in C++
I am writing an arduino library to post http request on web. I am using the String class from http://arduino.cc/en/Tutorial/TextString My code is behaving strangely when I am referring to my defined string objects after a function call. Here actually I am trying to get the body of my GET request and removing the http h...
If I understood correctly your code, you probably would want to do something like this: *response = response->substring(response->indexOf("\n\r\n"),response->length()); instead of response = &response->substring(response->indexOf("\n\r\n"),response->length()); Also there's probably no need to pass in a pointer ( refe...
2,057,610
2,057,629
STL Map with custom compare function object
I want to use the STL's Map container to lookup a pointer by using binary data as a key so I wrote this custom function object: struct my_cmp { bool operator() (unsigned char * const &a, unsigned char * const &b) { return (memcmp(a,b,4)<0) ? true : false; } }; And using it like this: map<unsigned...
You need to provide a comparator that guarantees non-modifying of the passed values, hence the const (note that it applies to the pointer not the char). As for the reference operator (&), you don't need it -- it's optional. This will also compile: struct my_cmp { bool operator() (unsigned char * const a, unsigned c...
2,057,784
2,057,879
Locking files in linux with c/c++
I am wondering if you can : lock only a line or a single character in a file in linux and the rest of the file should remain accessible for other processes? I received a task regarding simulating transaction on a file with c/c++ under linux . Please give me an answer and if this answer is yes ,give me some links from w...
Yes, this is possible. The Unix way to do this is via fcntl or lockf. Whatever you choose, make sure to use only it and not mix the two. Have a look at this question (with answer) about it: fcntl, lockf, which is better to use for file locking?. If you can, have a look at section 14.3 in Advanced Programming in the UNI...
2,057,823
2,057,904
Issues with Partial Class Function Overrides in C++
Is there any issue with partially overriding a set of virtual functions defined by a base class? My compiler provides the following warning: overloaded virtual function "MyBaseClass::setValue" is only partially overridden in class "MyDerivedClass". The classes look like this: class MyBaseClass { public: virtual vo...
The override for setValue(int) hides setValue(SpecialType*) of the base class (see the C++ FAQ Lite), so if you try to call setValue(new SpecialType()) you will get an error. You can avoid this by adding a using directive to the derived class that "imports" the overloads from the base class: class MyDerivedClass : publ...
2,057,946
2,057,987
How to mix std::string with Win32 functions that take char[] buffers?
There are a number of Win32 functions that take the address of a buffer, such as TCHAR[256], and write some data to that buffer. It may be less than the size of the buffer or it may be the entire buffer. Often you'll call this in a loop, for example to read data off a stream or pipe. In the end I would like to efficien...
std::string has a function c_str() that returns its equivalent C-style string. (const char *) Further, std::string has overloaded assignment operator that takes a C-style string as input. e.g. Let ss be std::string instance and sc be a C-style string then the interconversion can be performed as : ss = sc; // from C-sty...
2,057,960
3,380,861
how to set a threadname in MacOSX
In Windows, it is possible to set the threadname via this code. The threadname is then shown in debuggers. In MacOSX, I have seen several hints which indicates that there are threadnames. I think the class NSThread also has a name-attribute. My goal is that I can set the threadname in my C++ application and see it in X...
I recommend the following: [[NSThread currentThread] setName:@"My thread name"]; // For Cocoa pthread_setname_np("My thread name"); // For GDB. (You'll need to include pthread.h) Works a treat in XCode 3.2.3 (at least for iPhone development)
2,058,091
2,058,207
If-Then-Else Conditionals in Regular Expressions and using capturing group
I have some difficulties in understanding if-then-else conditionals in regular expressions. After reading If-Then-Else Conditionals in Regular Expressions I decided to write a simple test. I use C++, Boost 1.38 Regex and MS VC 8.0. I have written this program: #include <iostream> #include <string> #include <boost/re...
I think the format string should be (?1$1:000) as described in the Boost.Regex docs. Edit: I don't think regex_replace can do what you want. Why don't you try the following instead? regex_match will tell you whether the match succeeded (or you can use match[i].matched to check whether the i-th tagged sub-expression mat...
2,058,141
2,058,587
Reading SDL_RWops from a std::istream
I'm quite surprised that Google didn't find a solution. I'm searching for a solution that allows SDL_RWops to be used with std::istream. SDL_RWops is the alternative mechanism for reading/writing data in SDL. Any links to sites that tackle the problem? An obvious solution would be to pre-read enough data to memory and...
I feel bad answering my own question, but it preocupied me for some time, and this is the solution I came up with: int istream_seek( struct SDL_RWops *context, int offset, int whence) { std::istream* stream = (std::istream*) context->hidden.unknown.data1; if ( whence == SEEK_SET ) stream->seekg ( ...
2,058,159
2,058,318
How does the compiler know to use a template specialization instead of its own instantiation?
Consider the following files: Foo.H template <typename T> struct Foo { int foo(); }; template <typename T> int Foo<T>::foo() { return 6; } Foo.C #include "Foo.H" template <> int Foo<int>::foo() { return 7; } main.C #include <iostream> #include "Foo.H" using namespace std; int main() { Foo<int> f; cout <...
The issue is that you've violated the one definition rule. In main.C, you've included Foo.H but not Foo.C (which makes sense since it's a source file). When main.C is compiled, the compiler doesn't know that you've specialized the template in Foo.C, so it uses the generic version (that returns 6) and compiles a Foo cl...
2,058,271
2,058,321
Comparing String Iterator to Char Pointer
I have a const char * const string in a function. I want to use this to compare against elements in a string. I want to iterate through the string and then compare against the char *. #include <iostream> #include <string> #include <cstring> using namespace std; int main() { const char * const pc = "ABC"; string ...
Look at std::string::find: const char* bar = "bar"; std::string s = "foo bar"; if (s.find(bar) != std::string::npos) cout << "found!";
2,058,492
2,058,512
PyQt vs PySide comparison
I currently develop many applications in a Qt heavy C++/Python environment on Linux, porting to PC/Mac as needed. I use Python embedded in C++ as well as in a stand alone GUI. Qt is used fro xml parsing/event handling/GUI/threading and much more. Right now all my Python work is in PyQt and I wanted to see how everyone ...
We were recently thinking about using PySide, but we haven't found any information about whether it is supported by py2exe. That's why we kept to PyQt. If you need to develop for Windows, it's safer to use good ol' PyQt :-)
2,058,527
2,058,568
How to Set Baud Rate 28800 Using DCB Structure
Previously I was using CBR_9600 when communicating with 9600 baud devices. But there does not seem to be a CBR_28800 setting. Is it possible to set the baud rate using the DCB structure of 28800?
According to MSDN, the baud rate can either be one of the defined constants (such as CBR_9600, CBR_38400, etc) or any integer value. The constants are just defined to the values, so it's not really an enumeration at all. From the link: The baud rate at which the communications device operates. This member can be an ac...
2,058,634
2,059,001
why is stroull() not working on a byte array with hexadecimal values?
here is some new test code with regards to my long issue. I figure that if i code my stuff as long long then that is half the battle in porting. the other half would be to make it into big endian so it can work on any 64 bit system. so i did the following: #include <iostream> #include "byteswap.h" #include "stdlib....
If you're expecting this program to output "ab3254cd44" then you're using the wrong function. bytes is not a string. It's just an array of 5 values. Try this: int bytes[5] = {0xab,0x32,0x54,0xcd,0x44}; cout << hex; copy(&bytes[0], &bytes[sizeof(bytes)/sizeof(bytes[0])], ostream_iterator<int>(cout)); Program outputs: ...
2,058,700
2,058,710
Language recommendations for expanding programming skills (For a semi-experienced software developer)
I have little (<1 year professional) experience with Perl Groovy/Java I have limited (<2 year professional) C I have decent experience (>= 6 years professional) with PHP SQL I have hobby experience with C++/DX9 (some simple windows games/demos) Obj-C (a few iphone app's) ASM (http://www.amazon.com/Assembly-Langu...
Haskell, followed shortly by Python.
2,058,943
2,064,125
Reading SIM contacts on Symbian S60
I am looking for a working code snippet for Symbian S60 5th edition in which you can read SIM contact details. If possible, I would skip using RPhoneBookSession, but if that is the only way, please provide code snippet how to use it. Thank you.
What you want is the example code from the relevant chapter of the Quick recipes on Symbian OS book, which you can find here. EDIT-1: Should have read the question more carefully. The CContactDatabase API should synchronize with the SIM Phonebook seamlessly by using RPhoneBookSession so you don't have to. To figure out...
2,058,991
2,058,995
what does this declaration mean? exception() throw()
std::exception class is defined as follows exception() throw() { } virtual ~exception() throw(); virtual const char* what() const throw(); what does the throw() syntax mean in a declaration? Can throw() take parameters? What does no parameters mean?
Without any parameter, it means that the mentioned functions does not throw any exceptions. If you specify anything as a parameter, you're saying that the function will throw only exceptions of that type. Notice, however, this is not an enforcement to the compiler. If an exception of some other type happens to be throw...
2,059,058
2,059,110
C++ Abstract class operator overloading and interface enforcement question
(edited from original post to change "BaseMessage" to "const BaseMessage&") Hello All, I'm very new to C++, so I hope you folks can help me "see the errors of my ways". I have a hierarchy of messages, and I'm trying to use an abstract base class to enforce an interface. In particular, I want to force each derived mes...
The common convention for this is to have a friend output operator at the base level and have it call private virtual function: class Base { public: /// don't forget this virtual ~Base(); /// std stream interface friend std::ostream& operator<<( std::ostream& out, const Base& b ) { b.Print...
2,059,208
2,059,281
Derived class can't see parent class properly
I'm seeing two problems in a setup like this: namespace ns1 { class ParentClass { protected: void callback(); }; } namespace ns1 { namespace ns2 { class ChildClass : public ParentClass { public: void method() { registerC...
Change: registerCallback(&ParentClass::callback); ...to: registerCallback(&ChildClass::callback); The reason is because &ParentClass::callback is a fully-qualified typename, not resolved from the context of ChildClass but from global context. In other words, it is the same problem as this: class Thingy { protected: ...
2,059,363
2,059,368
Compile error when I use C++ inheritance
I am new to this website and I am trying a simple inheritance example in C++. I checked my code lots of times and I really see nothing wrong with it, however the compilers gives me errors: my code: #ifndef READWORDS_H #define READWORDS_H using namespace std; #include "ReadWords.h" /** * ReadPunctWords inherits ReadWo...
You need to include string: #include <string> That said, don't use using namespace! Especially at file-scope, and definitely not in a header file. Now any unit that includes this file is forced to succumb to everything in the std namespace. Take that out, and qualify your names: bool filter(std::string word); It's ar...
2,059,483
2,060,461
Installing poco library
im trying to install the poco library for visual c++ 2008 but when I type this command buildwin.cmd 90 I get the following error "'devenv' is not recognized as an internal or external command, operable program or batch file." The readme file says there is an alternate way to install poco from visual studio itself but ...
You can build the projects by opening the solution files in Visual Studio and build them from there.
2,059,665
2,059,705
Why can't I forward-declare a class in a namespace using double colons?
class Namespace::Class; Why do I have to do this?: namespace Namespace { class Class; } Using VC++ 8.0, the compiler issues: error C2653: 'Namespace' : is not a class or namespace name I assume that the problem here is that the compiler cannot tell whether Namespace is a class or a namespace? But why does this...
Because you can't. In C++ language fully-qualified names are only used to refer to existing (i.e. previously declared) entities. They can't be used to introduce new entities. And you are in fact "reopening" the namespace to declare new entities. If the class Class is later defined as a member of different namespace - i...
2,059,725
2,060,697
setting File Version automatically after compile
Is there any tool which can inject into an .exe or .dll information like File Version, Product name, Copyright, etc? I did find a tool called StampVer but it can only modify resources that are already in the file itself. I could use it but would need to modify a bunch of Visual Studio projects to include some dummy in...
I ended up adding a dummy resource version and will be using StampVer.
2,059,782
2,062,588
Pointer to a class and function - problem
Firstly I'll show you few classes. class A { public: B * something; void callSomething(void) { something->call(); } }; class B { public: A * activeParent; B(A * parent) { activeParent = parent; } void call(void) { activeParent->something = new C; } }; class C...
Aside from the design decisions (e.g., cyclical dependencies)... The only reason A's callSomething() method would call C's call() method from a pointer to B is if the call() method is virtual. To avoid calling C's call() method, here are a couple of options: Don't make the call() method virtual Rename one of B or C's...
2,059,804
2,059,888
Image format and unsigned char arrays
I'm developping imaging functions (yes I REALLY want to reinvent the wheel for various reasons). I'm copying bitmaps into unsigned char arrays but I'm having some problem with byte size versus image pixel format. for example a lot of images come as 24 bits per pixel for RGB representation so that's rather easy, every p...
You should do it like this: unsigned short NImage::get_pixel(int i, int j) { int offset = 2 * (j * pitch + i); // image pixels are usually stored in big-endian format return data[offset]*256 + data[offset+1]; }
2,059,895
2,060,648
Are there any automated unit testing frameworks for testing an in-house threading framework?
We have created a common threading framework to manage how we want to use threads in our applications. Are there any frameworks out there like gtest or cppunit that solely focus on unit testing threads, thread pools, thread queues, and such? Right now I just kind of manually go through some steps that I know I should ...
If your threads are built on OpenMP, you can use VivaMP for static checking. But you want dynamic checking with unit tests. I'm not aware of any existing framework for this purpose. You could roll your own with one of the many unit test frameworks out there, but it would be hard to make it robust. Intel has a suite of ...
2,059,914
2,059,927
Using Structs -- Odd Issue
Been awhile since I've used structs in C++. Any idea why this isn't working? My compiler is complaining about DataStruct not being a recognized type but Intellisense in VC++ is still able to see the data members inside the struct so the syntax is ok... Frustating. xD struct DataStruct { int first; }; int main(i...
Are you sure you are compiling the file as C++? If you compile it as C (i.e. if the file has a .c rather than a .cpp extension), you will have problems.
2,060,200
2,060,250
What is the best way to wait for a variable in a multithreaded application
I would like to do something like the below for a multi-threaded program: // wait for variable to become true but don't hog resources // then re-sync queues Is something like this a good solution? while (!ready) { Thread.Sleep(250); // pause for 1/4 second; };
No, this is not a good solution. First it might sleep too long. Second it's easy for threads to get into lockstep. Here's couple of links to MSDN articles on proper synchronization techniques: Conditional variables Events
2,060,403
2,060,440
Is there a better way to load a dll in C++?
Right now I do something like this and it seems messy if I end having a lot of functions I want to reference in my DLL. Is there a better and cleaner way of accessing the functions without having to create a typedef for each function definition so that it will compile and load the function properly. I mean the function...
After building your .dll get the .lib file nearby and link your test application with it. Use functions as they are declared in .h There's a minor change you need to do in your header file: #ifdef EXPORTS_API #define MY_API_EXPORT __declspec (dllexport) #else #define MY_API_EXPORT __declspec (dllimport) #endif ext...
2,060,578
2,060,631
Is it possible to write a varargs function that sends it argument list to another varargs function?
Possible Duplicate: C Programming: Forward variable argument list. What I'd like to do is send data to a logging library (that I can't modfify) in a printf kind of way. So I'd like a function something like this: void log_DEBUG(const char* fmt, ...) { char buff[SOME_PROPER_LENGTH]; sprintf(buff, fmt, <vararg...
You can't forward the variable argument list, since there's no way to express what's underneath the ... as a parameter(s) to another function. However you can build a va_list from the ... parameters and send that to a function which will format it up properly. This is what vsprintf is for. Example: void log_DEBUG(con...
2,060,735
2,067,321
Boost.MPL and type list generation
Background This is for a memory manager in a game engine. I have a freelist implemented, and would like to have a compile-time list if these. (A MPL or Fusion vector, for example). The freelist's correspond to allocation sizes, and when allocating/deallocating objects of size less than a constant, they will go to the c...
This is the best solution I came up with, and it's fairly simple. It requires a log and pow meta-template, which I've included for those who want to play or try it: #include <boost/mpl/for_each.hpp> #include <boost/mpl/range_c.hpp> #include <boost/mpl/transform.hpp> #include <boost/mpl/vector.hpp> #include <iostream> ...
2,060,742
2,060,783
C++ object class problems when used in another class
Having trouble when trying to create a class using another class(and 2 inner classes), I think it might be a syntax problem. The first class class listitem { //listitem.h(11) public: //MONSTER CLASS static class monster { public: monster(string thename); monster(void); ~monster(...
Did you protect your header with a #ifndef LISTITEM_H #define LISTITEM_H // All of your code #endif If not, it could be getting included twice, causing your error.
2,060,900
2,060,921
difference between foo[i] and foo->at(i) with stl vector
is there any reason why foo = (bar->at(x))->at(y); works but foo = bar[x][y]; does not work, where bar is a vector of vectors (using the c++ stl) the declaration is: std::vector< std::vector < Object * > * >
Is it a vector of vectors or a vector of pointers to vectors? Your code should work as advertised: typedef std::vector<int> vec_int; typedef std::vector<vec_int> multi_int; multi_int m(10, vec_int(10)); m.at(2).at(2) = /* ... */; m[2][1] = /* ... */; But your code appears to have: typedef std::vector<vec_int*> multi...
2,060,935
2,060,970
Easiest way to download HTML page from web?
I have a web page whose content I'd like to download into a wxString. For example, let's say that page is this: http://www.example.com/mypage.html And wxString would contain HTML source. In some other languages, say PHP for example, I would write something like this: $html = file_get_contents('http://www.example.com/...
If you are running on windows you could use the Microsoft WinHTTP library. However, having a quick look at the wxHTTP documentation, WinHTTP probably isn't any easier. Have a look at this straightforward wxHTTP sample code. It is doing exactly what you are after.
2,061,154
2,062,008
Byte swap of a byte array into a long long
I have a program where i simply copy a byte array into a long long array. There are a total of 20 bytes and so I just needed a long long of 3. The reason I copied the bytes into a long long was to make it portable on 64bit systems. I just need to now byte swap before I populate that array such that the values that go ...
Between this and your previous questions, it sounds like there are several fundamental confusions here: If your program is going to be run on a 64-bit machine, it sounds like you should compile and unit-test it on a 64-bit machine. Running unit tests on a 32-bit machine can give you confidence the program is correct ...
2,061,520
2,061,787
Is there a simple way to get scaled unix timestamp in C++
I'm porting some PHP to C++. Some of our database code stores time values as unix time stamps *100 The php contains code that looks a bit like this. //PHP static function getTickTime() { return round(microtime(true)*100); } I need something like this: //C++ uint64_t getTickTime() { ptime Jan1st1970(date(1970, 1...
The solution suggested by dauphic can be modified to something like this uint64_t getTickTime() { timeval tim; gettimeofday(&tim, NULL); return tim.tv_sec*100 + tim.tv_usec/10000; } I cant think of a neater solution than that.
2,061,558
2,072,109
streaming video to and from multiple sources
I wanted to get some ideas one how some of you would approach this problem. I've got a robot, that is running linux and uses a webcam (with a v4l2 driver) as one of its sensors. I've written a control panel with gtkmm. Both the server and client are written in C++. The server is the robot, client is the "control panel"...
Gstreamer solves nearly all of this for you, with very little effort, and also integrates nicely with the Glib event system. GStreamer includes V4L source plugins, gtk+ output widgets, various filters to resize / encode / decode the video, and best of all, network sink and sources to move the data between machines. For...
2,061,593
2,061,613
Why do C languages require parens around a simple condition in an if statement?
It sounds stupid, but over the years I haven't been able to come up with a use case that would require this. A quick google search didn't reveal anything worthwhile. From memory there was a use case mentioned by Bjarne Stroustrup but i can't find a reference to it. So why can't you have this in C languages: int val = 0...
If there are no brackets around expressions in if constructs, what would be the meaning of the following statement? if x * x * b = NULL; Is it if (x*x) (*b) = NULL; or is it if (x) (*x) * b = NULL; (of course these are silly examples and don't even work for obvious reasons but you get the point) TLDR: Bracke...
2,061,715
2,061,814
Unresolved external symbols in beginners CUDA program
I create a new Win32 Console App as an empty project I am running Windows 7 64bit with Visual Studio 2008 C++. I am trying to get the sample code from the bottom of this article to build: http://www.ddj.com/architect/207200659 I add CUDA Build Rule v2.3.0 to the project's custom build rules. It is the only thing wit...
I guess you are missing to link to the correct library. Make sure you have the CUDA library added under "Configuration Properties->Linker->Input". Refer this.
2,061,804
2,061,915
openssl BF_cfb64_encrypt thread-safety
Is openssl's BF_cfb64_encrypt() thread safe? A sample code to use it to encrypt / decrypt a blob of data would be much appreciated.
According to the FAQ, the OpenSSL routines are thread safe. I looked at the source of that function, and it does indeed appear to be thread safe. Of course, that assumes you are not passing the same input/output buffers to the function on different threads. For an example of a call to it, you should be able to look i...
2,061,885
2,061,939
boost regex sub-string match
I want to return output "match" if the pattern "regular" is a sub-string of variable st. Is this possible? int main() { string st = "some regular expressions are Regxyzr"; boost::regex ex("[Rr]egular"); if (boost::regex_match(st, ex)) { cout << "match" << endl; } else { cout << "not match" << ...
The boost::regex_match only matches the whole string, you probably want boost::regex_search instead.
2,061,947
2,061,959
Easy way to add text above all methods in a solution in VS 2005?
A colleague was working on a Perl script to consume a C++ source file and add text above all of the methods in the file. He was looking to develop code using regular expressions from the ground up to detect the top line of the method: void MyClass::MyMethod(int somethingOrOther) Trying to do this from scratch is frau...
You can do a regular expression search and replace. Since you can place new lines into replace box, you can go nuts and do anything you want(except for extracting parameters). Example forthcoming. Search string: ^:b*{:i}:b{:i}\:\:{:i}:b*{\(.*\)} Replace string: ///Regex Example\n///Class: \2\n///Method: \3 returning \1...
2,061,978
2,063,826
How do I align QtWidget to right in the QtToolBar?
I have some QtWidget (QtLineEdit) and I would like to align it to the right in my QtToolBar. Is there any simple way to do it? Thanks.
try putting spacer before it
2,062,171
2,064,275
HitTest not working as expected
I am wanting to display a context menu when a user right-clicks on an item within a CListCtrl. My code is as follows: void DatastoreDialog::OnContextMenu(CWnd *pWnd, CPoint pos) { // Find the rectangle around the list control CRect rectMainArea; m_itemList.GetWindowRect(&rectMainArea); // Find out if th...
I think HitTest() needs a position in client coordinates. It's been a while since I last did this, but it doesn't make sense to me to pass screen coordinates into a client window hit testing routine. Add m_itemList.ScreenToClient(&pos); before hitTestInfo.pt = pos; and see if that helps. Furthermore, note that OnContex...
2,062,242
2,062,333
C++ - Deleting a vector element that is referenced by a pointer
Well, I don't know if it is possible, but the thing would be: struct stPiece { /* some stuff */ stPiece *mother; // pointer to the piece that created this one }; vector<stPiece> pieces; Is it possible to erase the piece referenced by 'mother' from pieces, having just that pointer as a reference? How? Would it mes...
If your mother pointers point directly to elements of the pieces vector you will get in all kinds of trouble. Deleting an element from pieces will shift all the positions of the elements at higher indexes. Even inserting elements can make all the pointers invalid, since the vector might need to reallocate it's internal...
2,062,259
2,062,329
Using C/C++ to efficiently de-serialize a string comprised of floats, tokens and blank lines
I have large strings that resemble the following... some_text_token 24.325973 -20.638823 -1.964366 0.753947 -1.290811 -3.547422 0.813014 -3.547227 0.472015 3.723311 -0.719116 3.676793 other_text_token 24.325973 20.638823 -1.964366 0.753947 -1.290811 -3.547422 -1.996611 -2.877422 0.813014 -3...
Using C, I would do something like this (untested): #include <stdio.h> #define MAX 128 char buf[MAX]; while (fgets(buf, sizeof buf, fp) != NULL) { double d1, d2; if (buf[0] == '\n') { /* saw blank line */ } else if (sscanf(buf, "%lf%lf", &d1, &d2) != 2) { /* buf has the next text token, in...
2,062,316
2,062,383
Compiler optimization for fastest possible code
I would like to select the compiler optimizations to generate the fastest possible application. Which of the following settings should I set to true? Dead store elimination Eliminate duplicate expressions within basic blocks and functions Enable loop induction variable and strength reduction Enable Pentium instruction...
So I would like to know if any of the above options will speed up the application if I set them to true? I know some will hate me for this, but nobody here can answer you truthfully. You have to try your program with and without them, and profile each build and see what the results are. Guess-work won't get anybody a...
2,062,817
2,062,840
IcmpSendEcho and setting MTU size?
Does anyone know if its possible to adjust the MTU while sending an ICMP echo packet (with IcmpSendEcho)? I'm trying to do this under Windows using the IcmpSendEcho() function.
The maximum transmission unit (MTU) is a property of your network subsystem, it's not something that can be changed on the fly. Typical Ethernet, for instance, has a maximum MTU of 1,500 bytes. If you want to adjust the size of the request, it looks as if the fourth argument to IcmpSendEcho() is the size of the data to...
2,062,837
2,063,116
Help with type traits
Suppose we have the following template class template<typename T> class Wrap { /* ... */ }; We can not change Wrap. It is important. Let there are classes derived from Wrap<T>. For example, class NewInt : public Wrap<int> { /* ... */ }; class MyClass : public Wrap<myclass> { /* ... */ }; class Foo : public Wr...
You can do this using SFINAE but its kind of magical if you dont know whats going on... template<typename T> class Wrap { }; struct myclass {}; struct X {}; class Int : public Wrap<int> { /* ... */ }; class MyClass : public Wrap<myclass> { /* ... */ }; template< typename X > struct is_derived_from_Wrap { s...
2,062,881
2,063,075
How to skip common classes in VS 2008 when stepping in?
How can I skip common classes in VS 2008 debugger when stepping in? For example, I do not want debugger to step into any of the std:: classes. How can I achieve that? I've found ways of doing this in VS 2005 and earlier, but not 2008
You can do this by entering entries into the registry (I know, it sucks). The key you are looking for varies from 32 to 64 bit systems. For 32-bit systems the key is HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\9.0\NativeDE\StepOver If you're running a 64 bit OS and a 32 bit Visual Studio the key is HKEY_LOCAL_M...
2,062,956
2,062,982
Checking if an iterator is valid
Is there any way to check if an iterator (whether it is from a vector, a list, a deque...) is (still) dereferenceable, i.e. has not been invalidated? I have been using try-catch, but is there a more direct way to do this? Example: (which doesn't work) list<int> l; for (i = 1; i<10; i++) { l.push_back(i * 10); } it...
I assume you mean "is an iterator valid," that it hasn't been invalidated due to changes to the container (e.g., inserting/erasing to/from a vector). In that case, no, you cannot determine if an iterator is (safely) dereferencable.
2,063,037
2,063,083
Call my own Java code from C#
Having my own Java code I'm using C# to call some unmanaged code that call (via JNI) the java code. I'm using JNI since I need to ensure: the ability that the Java code will run over real JVM and not over some .NET VM the ability to attach to the VM for debugging (IKVM does'nt support it) I need free solution The curr...
You may need JNI, but your requirements don't really indicate it. The requirement to use a real JVM does not dictate the use of JNI. I'd suggest sharpening your requirements, or considering looser coupling. For example, socket comms, web services, a shared database, a shared file, or a queue. If you really need Jav...
2,063,328
2,064,061
Parallel for_each using openmp
Why does this code not parallelize std::for_each() when it works perfectly fine with std::sort()? How do I fix it? g++ -fopenmp -D_GLIBCXX_PARALLEL=1 -o p p.cc && time ./p sort GCC 4.3 on Linux. #include <cstdio> #include <algorithm> #include <vector> #include <cstring> void delay() { for(int c = 0; c < 1000...
Just compiling with -D_GLIBCXX_PARALLEL does not necessarily parallelize all algorithms (see here): Please note that this doesn't necessarily mean that everything will end up being executed in a parallel manner, but rather that the heuristics and settings coded into the parallel versions will be used to determine if a...
2,063,488
2,063,539
Interprocess communication
I have an API for a game, which calls methods in a C++ dll, you can write bots for the game by modifying the DLL and calling certain methods. This is fine, except I'm not a big fan of C++, so I decided to use named pipes so I can send game events down the pipe to a client program, and send commands back - then the C++ ...
After you create the pipe and have pipe handles, you read and write using the ReadFile and WriteFile APIs: see Named Pipe Client in MSDN for a code example. However, I'm at loss exactly how to use them. The "Named Pipe Client" section which I quoted above gives an example of how to use them. For example, what are t...
2,063,553
2,138,508
ComboBoxEx32 (CComboBoxEx) keyboard behaviour
I have a WTL application that uses an extended combobox control (the Win32 class ComboBoxEx32) with the CBS_DROPDOWNLIST style. It works well (I can have images against each item in the box) but the keyboard behaviour is different to a normal combobox - pressing a key will not jump to the first item in the combo that ...
In the end I hooked the combobox control (obtained with CBEM_GETCOMBOCONTROL) and trapped the WM_CHARTOITEM message and performed my own lookup. I can post code if anyone else is interested.
2,063,623
2,063,743
Qt's pragma directives
Could anyone point me out to an article, where pragma directives, available in Qt environment would be discussed?
AFAIK pragma directives are preprocessor and compiler directives and have not much to do with Qt itself. http://gcc.gnu.org/onlinedocs/cpp/Pragmas.html http://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html https://www.redhat.com/docs/manuals/enterprise/RHEL-3-Manual/gcc/pragmas.html Qt provides some defines, whic...
2,063,933
2,063,953
Listview controls don't appear in dialog
C++ win32 application (not MFC), whose GUI comprises just one dialog box from the resource file [WinMain() calls DialogBox()]. This works fine. However, adding any "common controls" (listview, tab control, etc) to the dialog and they don't appear when the program is run. Normal controls (textbox, button, radiobox etc...
Are you calling InitCommonControlsEx() in your program? Required.
2,064,103
2,064,823
Interprocess communication between C# and C++
I'm writing a bot for a game, which has a C++ API interface (ie. methods in a Cpp dll get called by the game when events occur, the dll can call back methods in the game to trigger actions). I don't really want to write my bot in C++, I'm a fairly experienced C# programmer but I have no C++ experience at all. So, the o...
One solution is to create a managed C++ class library with regular __declspec(dllexport) functions which call managed methods in a referenced C# class library. Example - C++ code file in managed C++ project: #include "stdafx.h" __declspec(dllexport) int Foo(int bar) { csharpmodule::CSharpModule mod; return mo...
2,064,138
2,064,255
Coding for ease of debugging
I am looking for tips on how to aid my debugging by adding code to my application. An example so that it becomes more clear what I'm after: in order to detect dangling objects held by shared_ptrs I have created a tracker class that allows me to keep track of how many objects are alive and where they where originally cr...
The following are mainly for ease of debugging after the release. Stackwalker and similar tools provide an easy way to get usable callstacks on end-user machines, with no debugger being active. Rather similar, Google Breakpad can be used to easily extract mini dumps from crashed processes.
2,064,334
2,064,394
How to check that all exceptions thrown have their matching catch clause
In java the compiler complains about uncatched exceptions. I use exceptions in C++ and I miss that feature. Is there a tool out there capable of doing it? maybe a compiler option (but I doubt it)
a static analyzer can run over your code and warn you if a function might throw an unhandled exception for example good old pc-lint or coverity
2,064,550
2,064,565
C++ : why bool is 8 bits long?
In C++, I'm wondering why the bool type is 8 bits long (on my system), where only one bit is enough to hold the boolean value ? I used to believe it was for performance reasons, but then on a 32 bits or 64 bits machine, where registers are 32 or 64 bits wide, what's the performance advantage ? Or is it just one of thes...
Because every C++ data type must be addressable. How would you create a pointer to a single bit? You can't. But you can create a pointer to a byte. So a boolean in C++ is typically byte-sized. (It may be larger as well. That's up to the implementation. The main thing is that it must be addressable, so no C++ datatype c...
2,064,553
2,064,599
What is a good resource to read about stack/heap and symbol table concepts?
Please suggest some website or some book that deals with these topics in really good detail. I need to have a better understanding of these concepts (in reference to C++): stack and heaps symbol tables implementation of scope rules implementation of function calls
You could read the Dragon Book, but I guess it might be too much.
2,064,692
2,064,722
How to print function pointers with cout?
I want to print out a function pointer using cout, and found it did not work. But it worked after I converting the function pointer to (void *), so does printf with %p, such as #include <iostream> using namespace std; int foo() {return 0;} int main() { int (*pf)(); pf = foo; cout << "cout << pf is " << p...
There actually is an overload of the << operator that looks something like: ostream & operator <<( ostream &, const void * ); which does what you expect - outputs in hex. There can be no such standard library overload for function pointers, because there are infinite number of types of them. So the pointer gets conver...
2,064,811
2,065,460
How do I compile a 64-bit version of ffmpeg on Windows?
i need to compile ffmpeg (64 bit shared dll) for windows. however I configure in mingw, it always produces 32 bit binary for me. tried this already ./configure --enable-shared --disable-static --enable-memalign-hack --arch=amd64 ./configure --enable-shared --disable-static --enable-memalign-hack --arch=x86_64 my guess...
See here for a 64-bit version of MinGW. The site even has 64-bit binaries of the ffmpeg library! UPDATE: Meanwhile it's easier to build on/for Windows, e.g. through ffmpeg-windows-build-helpers scripts.
2,065,228
2,065,497
is there a better way to select correct method overload?
Is this really the only way to get the correct address for an instance function: typedef CBitmap * (CDC::* SelectObjectBitmap)(CBitmap*); SelectObjectBitmap pmf = (SelectObjectBitmap)&CDC::SelectObject; First, one has to create a typedef, and then one has to use that to force the compiler to select the correct overloa...
What you're asking is similar to an earlier question, and the answer I gave there is relevant here as well. Conditional operator can’t resolve overloaded member function pointers From section 13.4/1 ("Address of overloaded function," [over.over]): A use of an overloaded function name without arguments is resolved in...
2,065,342
2,065,400
How to create a CString from an array of chars?
Need to log the content of buf using the LogMethod() below the problem is that LogMethos only accepts a "Const CString&" char buf[1024]; strcpy(buf, cErrorMsg); // need to pass to LogMethod "buf" how do i do that? log.LogMethod(const CString &); Thans Rev Reversed
If you're talking about MFC CString, as far as I can tell, it should have a non-explicit constructor taking TCHAR const *. In other words, the following should work. log.LogMethod(buf); If it doesn't, please post the error message.
2,065,392
2,065,769
C++ test if input is an double/char
I am trying to get input from the user and need to know a way to have the program recognize that the input was or was not a double/char this is what i have right now... but when you type an incorrect type of input 1) the double test one just loops infinatly 2) the char one won't stop looping even with the correct...
The problem is that when you read something and cin sees the input can never be a double, it stops reading, leaving the stuff in the buffer that it didn't consume. It will signal failure, which you clear but you won't eat the remaining input that cin didn't eat up. So, the next time the same wrong input is tried to rea...
2,065,938
2,065,961
Virtual destructor: is it required when not dynamically allocated memory?
Do we need a virtual destructor if my classes do not allocate any memory dynamically ? e.g. class A { private: int a; int b; public: A(); ~A(); }; class B: public A { private: int c; int d; public: B(); ~B(); }; In this case do we need to...
The issue is not whether your classes allocate memory dynamically. It is if a user of the classes allocates a B object via an A pointer and then deletes it: A * a = new B; delete a; In this case, if there is no virtual destructor for A, the C++ Standard says that your program exhibits undefined behaviour. This is not ...
2,066,090
2,066,268
Plotting waveform of the .wav file
I wanted to plot the wave-form of the .wav file for the specific plotting width. Which method should I use to display correct waveform plot ? Any Suggestions , tutorial , links are welcomed....
Basic algorithm: Find number of samples to fit into draw-window Determine how many samples should be presented by each pixel Calculate RMS (or peak) value for each pixel from a sample block. Averaging does not work for audio signals. Draw the values. Let's assume that n(number of samples)=44100, w(width)=100 pixels: ...
2,066,126
2,066,146
How can I count the number of characters that are printed as output?
Does anyone know how I can print and count the number of characters that I printed? Say I have a number I am printing via printf or cout. How could I count the actual number of digits I have printed out?
According to the printf man page, printf returns the number of characters printed. int count = printf("%d", 1000); If an output error is encountered, a negative value is returned.
2,066,180
2,066,195
the specified module could not be found 0x8007007E
Inside the constructor of a Form when I am stepping through my code, a method declared in the very same form is called. Before I can step inside the method, I get a System.IO.FileNotFoundException with message "The specified module could not be found. (Exception from HRESULT: 0x8007007E)". The member method I try to ...
The error is occurring when the .Net runtime JITs the method you're about to step into, because it couldn't find one of the types used by the method. What exactly does the method that you can't step into do, and what types / methods does it use?
2,066,184
2,066,197
How to use C++ String Streams to append int?
could anyone tell me or point me to a simple example of how to append an int to a stringstream containing the word "Something" (or any word)?
stringstream ss; ss << "Something" << 42; For future reference, check this out. http://www.cplusplus.com/reference/iostream/stringstream/
2,066,325
2,066,344
ways to add text to an image
In my C++ program, I want to be able to add some text over an image. I can already load/save the image, I just need to add text to it. I want to be able to use different fonts, colors, italics, bold, solid/transparent background, have a border around the letters, etc. I've done this in the past by using the old MFC fu...
GDI+ is what you are looking for. In .NET you will find the GDI+ classes in System.Drawing (requires assembly reference to System.Drawing.dll). Especially the class Graphics and its method Graphics.FromImage will help you.