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,438,482
5,438,502
Getting the current time as a YYYY-MM-DD-HH-MM-SS string
I'm trying to get the current time as a "YYYY-MM-DD-HH-MM-SS" formatted string in an elegant way. I can take the current time in ISO format from Boost's "Date Time" library, but it has other delimiting strings which won't work for me (I'm using this in a filename). Of course I can just replace the delimiting strings, b...
Use std::strftime, it is standard C++. #include <cstdio> #include <ctime> int main () { std::time_t rawtime; std::tm* timeinfo; char buffer [80]; std::time(&rawtime); timeinfo = std::localtime(&rawtime); std::strftime(buffer,80,"%Y-%m-%d-%H-%M-%S",timeinfo); std::puts(buffer); return...
5,438,550
5,438,577
How do I generate totally a random number at a time?
I want to create 3 random number at a time (simultaneously). However, they returned me the same numbers at a time even though they are actually random. Example: ------------------------ Variable: A B C ------------------------ Time 1 : 5 5 5 Time 2 : 3 3 3 Time 3 : 9 9 9 ---------------------...
Your issue here is you're resetting the random seed every call using the current time which you shouldn't do. Call srand() once before querying any random numbers - that's all and more than enough. Right now you always reset your random seed to the exact same value (as you use current time). Random numbers in PCs aren'...
5,438,613
5,561,696
Why can't I use a boost::function in an Objective-C++ block?
The following code throws an exception terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_function_call> >' what(): call to empty boost::function at the line f() (while executing the block): void foo(); // assume this is define...
It appears that if I modify the declaration with __block, it works correctly: __block boost::function<void()> f = boost::bind(&foo); I'm still not sure why this is - as @Richard mentions in a comment above, it must have to do with the "const copy constructor" as opposed to the "usual copy constructor". I don't know ho...
5,438,671
5,438,806
static_assert on initializer_list::size()
Why is std::initializer_list<_E>::size not allowable in a static_assert, even though it's declared as a constexpr in my libstdc++ (v. 4.6)? For example, the following code: template<class T, int Length> class Point { public: Point(std::initializer_list<T> init) { static_assert(init.size() == Length, "Wr...
The compiler says that init is the problem, not init.size(). I guess that the constructor could be called from different places with different length initializers. (To elaborate: You're trying to write a static_assert that depends on the run-time value of the variable init, namely how many elements it has. static_asser...
5,438,677
5,439,390
Is there something like ANTS Performance Profiler but for C++?
Possible Duplicate: Profiler for Visual Studio 2008, C++? Hi Are there any profilers for C++ ?? I need something which would investigate weak points of my application - by weak I mean not optimalized. Usualy I do this using ANTS Performance Profiler but this time my application is written in c++ and I don't know if...
If you want something simple but effective, there's this.
5,438,786
5,439,001
Finding Mode of Vector of Ints in C++
So I'm trying to make a basic program to learn the basics of C++, I'm generating 100 random numbers from 0 to 100 and storing them in a vector, I am then displaying the sum, mean, median, mode, high and low of the vector. I have everything else done except the mode which is where I get stuck. Here is the code I have so...
since all the values are between 0 and 100, you can find the mode efficiently with a histogram: std::vector<int> histogram(101,0); for( int i=0; i<100; ++i ) ++histogram[ numVector[i] ]; return std::max_element( histogram.begin(), histogram.end() ) - histogram.begin();
5,438,854
5,438,872
Anonymous Functors in G++?
I have some code that works in VS2008 but not in G++ that works as: struct IIterationFunctor { virtual bool operator()( SStateInfo& rStateInfo ) = 0; virtual ~IIterationFunctor() { } }; struct SNumItemsFunctor : public IIterationFunctor { SNumItemsFunctor (uint8& nNumItems, uint8 nItemType ) : m_nN...
The problem is that void IterateStateInfo( IIterationFunctor& functor ) isn't allowed to accept an anonymous temporary to bind to the non-const reference parameter. g++ is right to disallow it and MSVC is wrong. You need to make that parameter a const reference and it should work.
5,438,917
5,438,981
Get Memory Address of Binary Instructions
I'm currently working on some system level code where I would like to be able to identify the memory section(s) that are from the loaded binary in order to detect things like corrupted or modified instructions; Essentially what I'm after is a way, in Win32 using C++, to get a pointer to the range of instructions. This ...
You can find the entry-point to your code in the PE header. Download the PE (Portable Executable) file definition from MSDN - it has all the information. The format of the program in memory is virtually the same as it is on disk. From within the code, you can get a pointer to the PE header in memory via the GetModuleHa...
5,438,983
5,439,039
C++ Pointer Question
Can someone tell me what's wrong with this code? main: Book* test = new Book; char* end = "HelloThere"; test->reverseCString(end); char* Book::reverseCString(char* woot) { char* end = woot; while ( *end ) { end++; } end--; // Now we end is at the last letter // and woot is ...
char* end = "HelloThere"; String literal "HelloThere" is located in the read only location and is not modifiable. char* Problems::reverseCString(char* woot) { // Both woot and end are pointing to the string literal stored in // read only location. }
5,439,017
5,439,050
Which way to delete pointer: delete/delete[]/free?
I am implementing standart template tree structure, and I came across small problem. Idea that each node will hold pointer to some data. Later in order to delete element correctly I need to know if its a single pointer or pointer to an array. Inside of my tree->ReleaseMemory() method I have this code: if (node->_data ...
Don't do this at all. Use a smart pointer, like shared_ptr from C++0x or Boost or if that is not an option, auto_ptr from C++. If you could have more than one object, consider using std::vector. Manual resource management is messy and difficult to get right.
5,439,047
5,439,081
What does it mean for a binary to be 'munched' after it is compiled?
The title pretty much says it. This is w/regard to VxWorks; unfortunately, the documentation more or less says that it happens but not why or what purpose it serves.
It's been a few years since I had to deal with vxworks "munching", but what it does is create the C++ static constructor call table. It apparently isn't needed in the current (6.8+) versions that we're using now. What I recall was from 5.4, I think.
5,439,178
5,439,201
JNI calling JVM functions/events from native code?
I am wondering if it is possible for native functions to signal Java functions/events? Basically I think I will run some C++ code on a separate thread and do stuff like handling SIP and then for example if the native thread detects an incomming call, being able to signal the JVM somehow. I am not sure how communication...
There are several good articles around, like this one. Here's a Developer Works article that looks good too.
5,439,321
5,445,065
Implementation of Matlab's fmincon function in C++
We're currently using Matlab's fmincon function to do non-linear optimization for a project I'm working on. We need to port that part of the project to C++ in order to integrate it with other parts of the project. Is there a good way to compile the fmincon function into a library that we can use in C++? Or, is there...
Most of the time, libraries out there won't try to be a black box magic one-size-fits-all optimization tool like fmincon is- instead they'll require you to provide more detail and make more choices on your own, which is simpler for them and should result in your software being faster. You can certainly use the MATLAB E...
5,439,380
5,439,464
How to Incorporate a memory allocator in C++
I am working on a lock free data structure, and I have been examining the code at libcds, but I can not seem to figure out how to incorporate there memory allocator into my class file. template<class KEY, class VALUE> class DataStruc{ public: I have never used custom memory allocators before, and I am having trouble ...
You just need to implement operator new() for your class. Your implementation should get memory from an instance of the allocator. In the header file for your class, you'll need to declare the allocation/deallocation operators: public: void * operator new(size_t size); void * operator delete(void * obj, size_t ...
5,439,393
5,439,476
Const References to Pointers
I came across some code that used a method like this: QList<Item*> itemList; void addItem(Item* const& item) { itemList.append(item); } Now, I can't see any meaningful difference between that and this: QList<Item*> itemList; void addItem(Item* item) { itemList.append(item); } But obviously someone went way out...
The only difference is that in the first version you would not be allowed to change the value of the local item inside the function (you could still modify the Item it points to). Therefore if you wanted an Item* to hold a different value for some reason, you 'd be forced to use another local of type Item* and the func...
5,439,587
5,439,651
Accessing windows registry under GCC/C++
I'm trying to access windows registry using standard windows api. I'm using mingw c++ compiller. Please tell why this code crases at line (X) HKEY hKey; DWORD dwDisp = 0; LPDWORD lpdwDisp = &dwDisp; QString value = "String Value"; LONG iSuccess = RegCreateKeyEx( HKEY_CURRENT_USER, TEXT("HKEY_LOCAL_MACHINE...
Take a look at the function description again. If you want to set the default value for the key you need to do something like this: TCHAR szData[] = TEXT("1234") RegSetValueEx(hKey, NULL, 0, REG_SZ, (LPBYTE)szData, sizeof(szData)); If you actually want to specify the value name: TCHAR szData[] = TEXT("1234") RegSetVal...
5,439,649
5,442,304
Boost Thread dies before job finished
I am using the boost library to implement a socket communication. In respect to my main application, a connection handler should be launched who deals with all incoming requests. Therefore I have encapsulated the whole server handler into the class server. When the server object is created it should launch the server. ...
Your io_service needs to be primed with some io_service::work to do, either explicitly or from your tcp_server object. Otherwise io_service::run() will return control immediately. Study the asio examples, this concept is important to understand. The work class is used to inform the io_service when work starts and fini...
5,439,811
5,439,835
How can you use a "function type"?
In C++ you can create a "function type" with for example: void main() { int a(); } And a has the type "int ()", but is it possible to use it? I can't even pass 'a' as a template argument (but I can pass "int ()" as one)
You are not declaring a "function type". You are declaring a function. This is the same thing that you normally do in file scope, but in this case you do it in local scope int main() { int a(); /* declare function `a` */ ... int i = a(); /* call function `a` */ } int a() { /* define function `a` */ /* whate...
5,440,089
5,440,268
How to "pattern match" a template?
Normally in templates you want to know the entire type, but in my case I need to know more, and want to "break up" the type. Take this example: template <typename Collection<typename T> > T get_front(Collection const& c) { return c.front(); } How can I achieve that? Note: I need it to to automatically deduce the typ...
Edit: A C++0x way can be found at the end. Edit 2: I'm stupid, and a way shorter C++98/03 way than all this traits stuff can be found at the end of the answer. If you want your function to work for any arbitary standard library container, you need to pull out some Template Guns. The thing is, that the different cont...
5,440,154
5,440,167
Default constructor C++ error
I require help with respect to class construction. In my class, I have used a copy constructor and operator= to prevent the compiler from creating them. In my main program, when I try to create an instance of the class, I get an error saying "No default constructor exists for the class". What could be the problem? This...
There are two problems with the code - class members are private by default. "I get an error saying "No default constructor exists for the class" ". Because if any kind of constructor is provided as a part of class declaration( netlist class has a copy constructor in this case), default constructor( i.e., constructor...
5,440,248
5,440,301
boost::variant and getting data to encode for msgpack
I am using boost recursive variant to store the variant data which I want to encode using msgpack for which I need to get the raw data to pass into encode() function (see below). I tried three different options in encode() function below but doesn't work. What are the alternates? typedef std::vector<boost::recursive_v...
I don't think you're using std::type_info in a way that works with Boost::Variant. Idea: Use the code similar to that provided here to wrap your calls to encode your own tag. By using a visitor, you'll essentially restrict yourself to the public interface of the Boost.Variant library. Alternative: use variant.which Do...
5,440,336
5,440,383
How do I tell a wstring that a string I am feeding it is already a wstring?
I am using a std::string as a text buffer. Then, I am sure the data contained in that buffer is UTF-16 (i.e. it is really a std::wstring). How can I coerce a std::string into a std::wstring? The std::string is a misnomer, the data is really a wstring.
Consider using a std::vector<char> instead of a std::string. It's the correct container when you want "a contiguous sequence of bytes." With a std::vector source container, the code is rather straightforward, assuming you really just want to reinterpret the data (i.e., you really just want to treat the bytes as if the...
5,440,497
5,440,503
Very simple c++ for statement but it wont cout?
My question is simple. I have a 'for' statement in a c++ program and when I compile ignores my cout. I am using xcode, compiling with xcode and here is my code: #include <iostream> using namespace std; int main () { cout << this prints" << endl; for(int i=0; i>10; i++) { cout << "t...
for(int i=0; i>10; i++) You initialize i to 0 then only enter the body of the loop if i is greater than 10. The loop loops as long as the condition i > 10 is true, not until the condition i > 10 is true. This is how all the loops in C++ work: for, while, and do/while.
5,440,551
5,440,567
Why _WIN32_WINNT == 0x400 in Qt Creator on Windows 7 machine?
I'm using Qt Creator 2.0.1 based on Qt 4.7.0 (32 bit). The OS is Windows 7 Ultimate (32 bit). I'd like to restart Windows using the following function call: ExitWindowsEx(EWX_REBOOT, SHTDN_REASON_MAJOR_SYSTEM | SHTDN_REASON_MINOR_NETWORK_CONNECTIVITY); I've added windows.h and reason.h in the...
The value of _WIN32_WINNT indicates the version of the Win32 API you're targeting at runtime. It has nothing to do with the version of the OS you happen to be using while doing the build. If you set this to a higher value before including the API header files more API functions and definitions will become available, b...
5,440,682
5,440,803
STL vector vs list: Most efficient for graph adjacency lists?
Lists consume most of their time in allocating memory when pushing_back. On the other hand, vectors have to copy their elements when a resize is needed. Which container is, therefore, the most efficient for storing an adjacency list?
I don't think this can be answered with absolute certainty. Nonetheless, I'd estimate that there's at least a 90% chance that a vector will do better. An adjacency list actually tends to favor a vector more than many applications, because the order of elements in the adjacency list doesn't normally matter. This means w...
5,440,781
5,440,905
sorted atomic linked list algorithm (priority queue)
Can somebody point me towards an algorithm for a sorted thread-safe atomic (lock-free) linked list/priority queue? I'm aware of how to do just a linked list itself, but now I need one that is sorted. I'm unsure if this is minor change or significant redesign compared to an unsorted list, thus would like to see an exist...
Look at this: "Fast and Lock-Free Concurrent Priority Queues for Multi-Thread Systems". Googling will give you more links for sure.
5,441,248
5,441,419
C++ using && with your class without bool/&& overload?
I was told that you can in fact do MyClass a, b; ... if (a && b) {...} without 1) overloading the && operator 2) overloading the bool operator (ex: class MyClass { ... operator bool(){return boolval; } };) The solution was to use a pointer-to-member-function. I did not understand how to use this solution. My notes say ...
Note: Typically answers to [homework] questions do not immediately give away the solution. However, according to your question you already know the solution but don't understand it. I'll attempt to explain. From the information you provided in your question, your instructor was probably talking about some variant of th...
5,441,264
5,489,746
Using an accepted connection as a socket (cpp-netlib)
Is it possible to get an accepted connection via cpp-netlib and use it like a normal TCP Boost.asio socket?
The socket_ member of boost::network::http::impl::http_async_connection is private, but that would be the member that contains the TCP socket you're looking for, so the short answer is "no"
5,441,274
5,441,331
C++ example of implementation composite and visitor pattern together
Now I'm developing a specialized vector editor. Can you tell me where I can see a good example (only C++ language ) of source (not standard book example) implementation composite and visitor pattern together.
Composite + visitor isn't such a popular pair, in most cases you can see composite + iterator ... so you will have to try add them by your own hands, but it shouldn't be hard. In both patterns you have inteface implemented by concrete classes, so you have to fill your composite with visitor ideas http://sourcemaking.co...
5,441,316
5,441,595
I'd love comments on this template design idea I'm playing around with
I've been teaching game programming and I've spent a lot of time talking about breaking dependencies with the goal that old code should not change if new code is introduced. We were setting up a renderer object and I decided to templatize the render function so I could show some uses for traits classes, etc. But this l...
If I'm correctly understanding your description: template <class> class render; // undefined template <> class render<Object1> { // ... }; template <> class render<Object2> { // ... }; // ... I consider this a valid approach. Sometimes you can fill out the general case primary template, and sometimes you can...
5,441,401
5,443,085
Compressing Iplimage to jpeg on memory
I am working on a project that I will transfer webcam images on the network , real time. But Iplimage has a big size so it does not fit in a udp packet. I have to compress it to jpeg format. I made some research many examples do save the picture on disk then read to the memory. But I want do it on memory. I am using Qt...
Qt has QImageWriter class which supports JPEG format and allows specifying compression level. You can use it to save QImage data to QByteArray. Below is an example: QImage image("/home/image_from.png"); QByteArray array; QBuffer buffer(&array); // write image to memory buffer QImageWriter writer; writer.setDevice(&b...
5,441,436
5,441,446
My static map is always empty
I declared a static unordered map in a header file as follows: static boost::unordered_map<KeyAction, sf::Key::Code> WindowKeyMap; in that same header file, i have a function that fills the map with some values: static void Initialize(std::string &file) { WindowKeyMap[MoveLeft] = sf::Key::Code::Left; WindowKey...
When you declare your variable in the header like that each compilation unit (*.cpp) gets it's own local static copy. You have to declare it extern extern boost::unordered_map<KeyAction, sf::Key::Code> WindowKeyMap; and in one cpp put boost::unordered_map<KeyAction, sf::Key::Code> WindowKeyMap;
5,441,464
5,442,076
How to make timer for a game loop?
I want to time fps count, and set it's limit to 60 and however i've been looking throught some code via google, I completly don't get it.
You shouldn't try to limit the fps. The only reason to do so is if you are not using delta time and you expect each frame to be the same length. Even the simplest game cannot guarantee that. You can however take your delta time and slice it into fixed sizes and then hold onto the remainder. Here's some code I wrote rec...
5,441,497
5,441,604
Changing backslash to forward slash in a QString
I have a program that gives a QString and changes every "\" to "/". It seems very simple but when I use the below code, 5 errors happen: QString path ; path = "C:\MyLife\Image Collection" ; for( int i=0 ; i < path.size() ; i++ ) { if( path[i] == "\" ) path[i] = "/" ; } qDebug() << path ;
Please, Stop the bleeding, now ! And use a cross-platform directory/path wrapper class. Qt have some : QDir, QFileInfo, QFile. Just use them. ooh, and QDir have a nice static method for you, which does exactly what you want : path = QDir::fromNativeSeparators(path); No excuse to do it manually (with bugs)
5,441,762
5,441,768
a bit map in c++ - will unsigned int do the job?
I'm afraid to admit, I haven't used C++ for a while now but i'm afraid I have to now, and I'm a bit rusty. I need to have a bitmap, and I do care about performance, my bitmap size will be no longer then 25 bits. I was thinking about using unsigned int, but I am afraid I do not remember how it is implemented in c/c++ I...
Use an std::bitset<25> from the header <bitset>. bitset can be indexed with [] and is a template, so it likely expands to just an unsigned int (or equivalent) with all operations inlined.
5,441,866
5,441,980
Are any language bindings available for NSSpeechSynthesizer Cocoa class?
I know that i can use PyObjC to access Cocoa objects in Python. Can i do this with C++? What other languages can i use?
You can call objective C classes directly from Objective-C++ (.mm extension). Objective-C++ allows you to mix C++ and Objective-C Also from the wikipedia page: The Cocoa frameworks are written in Objective-C, and hence Objective-C is the preferred language for development of Cocoa applications. Java bindings fo...
5,441,884
6,513,628
Why does explicit constructor of boost::shared_array cause an error?
boost::shared_array<char const *> x(new char const *[n]); In the line above (n is integer number not greater than 100) I'm creating char const**(const char**) and putting it to smart pointer x for arrays to be deleted when x is deleted. And for me it is clearly how and why this work. boost::shared_array<char const *> ...
Now lets take a look to second line. Here in my opinion we do exactly the same as in first case. Yes at first glance we may seem that here we constructing x via NULL(default value of shared_array constructors parameter) then calling operator=, but this is mistake, and as I know in this case instead of op...
5,441,893
5,441,944
What is singular and non-singular values in the context of STL iterators?
The section §24.1/5 from the C++ Standard (2003) reads, Just as a regular pointer to an array guarantees that there is a pointer value pointing past the last element of the array, so for any iterator type there is an iterator value that points past the last element of a corresponding container. These value...
Iterators can also have singular values that are not associated with any container. I suppose that's its definition. How and why dereferenceable values are always nonsingular? Because if they wouldn't, dereferencing them would be undefined behavior.
5,442,059
5,442,083
How to access to memory block which allocated by std::vector?
Many people recommend vector class for variable length array. And I have to pass pointer to memory block to GL. How can I access pointer to memory block allocated by std::vector?
Use the address of first element. If your vector is v then &v[0] will work.
5,442,184
5,442,202
Should I clean up ivar C++ vector...?
If a vector is placed in stack, it will be destructed automatically at the end of its automatic variable scope. What if I have placed a vector in a class? class A { vector<B> bs; // B is POD struct. }; Should I clean it up manually? If so, how should I do?
That vector bs will be destructed when the enclosing class's destructor (i.e A's destructor) will be called. void f() { { A a; //working with a; }//<--- here a goes out of scope, so it's destructor is called; //so not only a is destructed but also a.bs }
5,442,275
5,442,378
Kruskal's algorithm and disjoint-set data structure: Do I need the following two lines of code?
I've implemented Kruskal's algorithm in C++ using the disjoint-set data structure according to Wikipedia like this: #include <stdio.h> #include <algorithm> #define MAX_EDGES 10000000 #define MAX_VERTICES 200001 using namespace std; int num_edges,num_vertices; int total_cost=0; struct edge{ int v1,v2; int cost;...
1) findset(x) returns the canonical representative of the set that x is in (the root of its ancestry tree). You need this to be able to compare whether two elements are in the same set or not (they have the same representative), parent[x] just returns the parent of x in the tree, which may not be the root. 1a) You forg...
5,442,459
5,442,476
how to call h files in c++ project
first i created a folder name 'C:MyProject' and then another 2 folders inside the 'MyProject' have created called 'src' and 'include'.After that i opened a new project in c++ and saved it in the 'MyProject' as myproject.dev. then i added 2 folders to my project for that i used same name which i created in my project fo...
When the prepocessor reads #include "a.hpp" it looks for a.hpp in the current folder. In your case, it means src. But your header files are not there ! They are in C:/MyProjects/include. You need to tell the compiler where to look for include files. Usually it's something called "include directories" in the project opt...
5,442,526
5,442,576
C++ float number to nan
I want to know what makes a float number nan in c++. I am using a large dataset and it is really hard to trace. I want to know the ways of changing a float number to nan to reduce bug possibilities. I found the code that causes the nan problem. I found that s/m is nan in some cases. But I don't know how to solve it. fl...
Taken from wikipedia -> special values -> nan 0/0 ∞×0 sqrt(−1) in general "invalid operations" (I am not sure wether there are not more than the three above) Looking at you code: infinity times 0 is possible, is it? edit: 0 <= s <= +inf 1 <= m <= +inf s / m: +inf / +inf does indeed make minus NaN (I tested it) I ...
5,442,596
5,442,608
Comparing data types
int item; cin >> item; That's in my code, but I want the user to be able to type integers or strings. This is basically what I want to do: if(item.data_type() == string){ //stuff } Is this possible?
no, but you can input string and then convert it to integer, if it is integer.
5,442,673
5,442,691
Understanding some C++ code
I dont understand the part: struct tm * timeinfo; what does this mean? Why there's a star there? Thanks! int main () { time_t rawtime; struct tm * timeinfo; time ( &rawtime ); timeinfo = localtime ( &rawtime ); printf ( "The current date/time is: %s", asctime (timeinfo) ); return 0; }
struct tm * timeinfo; It's declaring a variable timeinfo of type struct tm*. This is C-syntax. In C++, you don't need to write struct keyword. Just tm * timeinfo is enough!
5,442,717
5,442,736
Can't C++ POD type have any constructor?
I have a class and a const variable. struct A { int b; }; A const a; The class A is POD and can be initialized like this. A const a = { 3 }; IMHO, it looks fine to have a constructor like this. struct A { int b; A(int newB) : b(newB) { } }; But Clang assumes A as non-aggregate type. Why I can...
POD means Plain Old Data type which by definition cannot have user-defined constructor. POD is actually an aggregate type (see the next quotation). So what is aggregate? The C++ Standard says in section §8.5.1/1, An aggregate is an array or a class (clause 9) with no user-declared constructors (12.1), no private o...
5,442,749
5,445,554
Static Lib To Help With Dll Plugins In C++
I'm an indie game developer, who previously focused on XNA. Currently I'm making the transition to native C++ and DX10. My latest project is an RPG and I have finished an early alpha version, but I want to do a complete rewrite for my next version (following the "make it work, make it clean, make it fast" principle). G...
Yes I would go with the static lib. As for versioning, while you cannot version the lib itself you can solve this by simply hosting your lib in a public source repository and naming it with the version number matching the current version of your gaming engine.
5,442,826
5,442,836
Writing a string to file in binary mode
So I'm using this code to write the file(just testing now, I'm going to write a level editor later): int main() { ofstream file("level.bin", ios::binary); int ents = 1; //number of entites file.write((char*)&ents, sizeof(int)); float x = 300; //x and y coords float y = 500; file.write((char*)&...
The error is at this line: file.write(img.c_str(), sizeof(img.c_str())); What you want is: file.write(img.c_str(), img.size()); The sizeof(img.c_str()) returns 4 because sizeof(char *) (the return type of c_str()) is 4 on your platform. This means first 4 characters are written and then you get just some garbage.
5,443,031
5,443,856
How to embed CCmdTarget-derived class into MFC message chain?
I want to extract some settings-specific code from View class and put it in to CSettings class. I don’t want to bloat my CView class when amount of settings will be more than 80. All the messages from Menu (and ribbon) about settings should be processed in CSettings class. The only thing I can't understand is how to em...
You don't have to add anything to your view class's message map. Instead you should override the OnCmdMsg function to route the command and update messages to your CSettings class, like this: class CMyView : public CView { // ... virtual BOOL OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINF...
5,443,073
5,443,851
Read a line from xml file using C++
My XML File has: < Package > xmlMetadata < /Package > I am searching for a tag in this file and the text between the starting and closing tags of this has to be printed on console. i.e. in this case I want xmlMetadata to be printed on the console. Similarly it should go further in the file and print again if ...
This is not the way you should parse an XML file, but since you don't want to use a parser library this code might get you started. File: demo.xml <? xml version="1.0" ?> <fileStructure> <Main_Package> File_Navigate </Main_Package> <Dependency_Details> <Dependency> <Package> xmlMetadata </Package> <H...
5,443,119
5,443,163
Is static data member typed its container type possible in C++?
I was used something like this in C# or other languages. // C#, but I can't remember correctly. Just assume like a pseudo code. class A { public int b; public A(int newB) { b = newB } public static const A a1 = A(1); public static const A a2 = A(2); public static const A a3 = A(3); }...
Is there equivalent of this in C++? The following C++ code is equivalent to your C# code: class A { public: int b; A(int newB) : b(newB) { } //declaration static const A a1; static const A a2; static const A a3; }; //definition - necessary! const A A::a1 = A(1); const A A::a2 = A...
5,443,227
5,443,236
C++ - Unhandled exception when using atoi()
When using this code, it throws an unhandled writing exception, which I'm almost certain is to do with the atoi() function. while(true){ char* item = ""; cin >> item; int numItem = atoi(item); if(numItem){ if(numItem...
Use: char item[20]; char * item = "" makes item point to read-only memory - you're trying to modify it. Pointers to string literals are better written as const char * item = "" - then the compiler will make sure you don't modify it. The reason char * item = "" is legal is backward compatibility with C.
5,443,475
5,443,495
How do you compile C++ source code that includes C source file?
I'm attempting to use SQLite in a c++ program. My knowledge of C/C++ is limited as I've mostly used Java to this point. I had some classes in college but its been a while and we never covered anything like this. SQLite is written in C. When compiling the program how would you do this? (I have MinGW installed on my ...
You protect the C headers in your C++ code by extern "C" { // your includes here } and that should be all---g++ should happily link code from both gcc and g++. The extern "C" ... trick is also used in C++ system headers and many libraries, just look at the headers that came with your g++ installation or some s...
5,443,479
5,443,537
How to convert QString to LPCSTR (Unicode)
how can I convert QString to LPCSTR ? How do I do it when #ifdef UNICODE is defined and when it isn't ? Thanks very much :)
I guess: QString str("ddddd"); LPCSTR lstr = str.toStdString().c_str();
5,443,493
5,443,557
confused about MFC/.net/WPF
I want to create a desktop application for windows, I know there's one type of application based on Win32 API and another based on the .net framework. So what is with the MFC, WPF, WinForm etc.? From what I've seen they are graphical APIs, so which would I choose for my application? And is there any good resources (e.g...
MFC is a framework for creating GUI applications in native (unmanaged) C++ like the C++ you learned in college. The .NET Framework supports writing managed code in C++/CLI, C#, VB.NET or a number of other languages. There are two ways of building a desktop GUI application on the .NET Framework - Windows Forms and WPF. ...
5,443,676
5,443,692
Creating metadata for binary file
I have a binary file I'm creating in C++, I'm tasked to create a metadata format to describe the data that it can be read in Java using the metadata. One record in the data file has Time, then 64 bytes of data, then a CRC, then a new line delimiter. How should the metadata look to describe what is in the 64 bytes? ...
Probably you want to generate a file which describes how many entries there are in the data file, and maybe the time range. Depending on what kind of data you have, the metadata might contain either a per-record entry (RawData, ImageData, etc.) or one global entry (data stored as float.) It totally depends on what the ...
5,443,870
5,444,087
Reading a BMP into memory using the correct structures
I'm currently doing a steganography project (for myself). I have done a bit of code already but after thinking about it, I know there are better ways of doing what I want. Also - this is my first time using dynamic memory allocation and binary file I/O. Here is my code to hide a text file within a BMP image: Link to co...
The size of the color table is determined by bV5ClrUsed. An ICC color profile is present in the file only if bV5CSType == PROFILE_EMBEDDED. The documentation here provides all that information. Then, 24-bit color means 8 red, 8 green, 8 blue, 0 alpha. You'd have to convert that to 32-bit RGBA in order to have any alph...
5,444,111
5,444,886
Bigendian/Littleendian confusion
i am working on the legacy code, which is written for ipv4. Now i have added the similar code for ipv6. i have tried and tested on host machine..but i have concern whether it will work on the powerpc , because of endianness...the code is to extract the ip header from the incoming stream and compress it..any comments wi...
Bitfields and portability are generally a nightmare. It is usually better to use and/or/shift. See e.g. below. As long as you call hton*()/ntoh*() on the various integers as you read/write them you will (hopefully) have no problems. I'd also write the rest of the accessors and make the data fields private. class st_...
5,444,211
5,444,225
for loop is giving different result than +=
I really do not understand what is happening here but: when I do: colorIndex += len - stopPos; for(int m = 0; m < len - stopPos; m++) { colorUniPos++; } it does not give me the same result as doing: colorIndex += len - stopPos; colorUniPos += len - stopPos; I think it becomes off by one or something. Shouldn't bo...
This won't produce the same result if len - stopPos < 0
5,444,303
5,444,458
Loop unrolling vs Loop tiling
Can someone please tell if the 2 optimization techniques are same or different? Also, is it responsibility of programmer or compiler to do it?
The two techniques are different. See descriptions for Loop unrolling and Loop tiling. Loop unrolling is done to eliminate the overhead of looping. It is (usually) only useful for fairly small loops where the number of iterations is small and is known at compile time. It is mostly done by the compiler. In older t...
5,444,327
5,444,534
std::set of boost::weak_ptr<T> - Getting const_iterator to const T?
I have class containing an std::set of boost::weak_ptr<T>. I have two functions begin() and end() that return an iterator to the container. However, I don't want clients to be able to modify T. Simply returning a const_iterator won't work, because the T pointed to by the boost::weak_ptr will be editable. What I want to...
You can write a transform iterator to convert the weak_ptr<T> to a weak_ptr<const T>. Since you're already using Boost, you can use boost::transform_iterator: #include <boost/iterator/transform_iterator.hpp> #include <boost/shared_ptr.hpp> #include <boost/weak_ptr.hpp> #include <set> // Functor to transform a weak_p...
5,444,489
5,444,531
Wrong Values in Array of Double
I have problem in getting wrong values in array of double. Instead of getting the values that I'd like to have in "printf" after defining the array's values one by one, I got 0 instead const int M=20; const int K=2; typedef double polybasis[M][K+1][K+1]; polybasis Phik; for(i=1; i <= M; i++){ ...
C++ array indices are zero-based. The index must always be less than the extent of the array. For example, your first three loops should probably be: for(i=0; i < M; i++){ for (j=0; j <= K; j++){ for (k=0; k <= K; k++)
5,444,824
5,444,849
Building a client-server application for local programming contest system
I am thinking to build a client server system, in which the server can receive user's code and compile it and return the result to the user. This system will be used for a local online programming contest at my university. So basically, the user can write some code (PHP / C++ / Java, etc) and submit their code from th...
Check out Hudson, we use it at our company and it compiles our applications through Ant then gives us the compiled applications in rpm's.
5,444,860
5,444,923
including files problem
I have test.h file and example.h file and I want to include each one in the other I tried the following but didn't work. In file test.h: #ifndef "example.h" #define "example.h"` ... #endif And in file example.h : #include "test.h" And later tried : #ifndef "test.h" #define "test.h" ... #endif But nothing ...
You need to come up with some unique identifiers for each include guard. For example: #ifndef EXAMPLE_H #define EXAMPLE_H ... #endif You can't just use the filenames with #ifndef etc.
5,444,913
5,444,957
Program gives LNK2019 error even after including header files
I am trying to understand how including multiple files in C++ works. I did a lot of searching and finally I wrote a test code which is summarizes my problem. I have two header files and two cpp files that look like this: test1.h: #ifndef _TEST_1_H #define _TEST_1_H int val = 10; void func1(); #endif test2.h: #ifndef...
Including the files only satisfy the compiler. You need to link all of the obj files together. If you are using visual studio, make sure all of those files are included in the project you're building. One a side note, using int val = 10 on the header file is wrong - you'll have linkage problem. Put it in a cpp file an...
5,444,918
5,445,031
Virtual not permitted on data declarations
When trying to declare an abstract class, I don't seem to be able to have templated functions. Why is this, and how do I deal with it? Here is my example header file. // Foo.h #include "Bar.h" #include "Baz.h" class Foo { public: Foo(); virtual Bar<Baz> *getBaz() const = 0; //snip }; Other compiler ...
I looks like it does not recognize Bar as a type. Check your two header files and make sure: 1) That it is defined 2) The include guards are correct and it is not hidden.
5,444,959
5,445,381
Read a text file line by line in Qt
How can I read a text file line by line in Qt? I'm looking for the Qt equivalent to: std::ifstream infile; std::string line; while (std::getline(infile, line)) { ... }
Use this code: QFile inputFile(fileName); if (inputFile.open(QIODevice::ReadOnly)) { QTextStream in(&inputFile); while (!in.atEnd()) { QString line = in.readLine(); ... } inputFile.close(); }
5,445,023
5,445,382
C++ - Can you build one static library into another?
I ran into a strange problem with a Visual Studio 2008 project I was working with recently. I am trying to compile a new static library that uses functions from another static library. (Let's say Lib1 is my static library project, and Lib2 is the lib file that Lib1 depends on). I am able to build lib1 without issue; It...
I would not advise using a librarian to take Windows' library contents into your own library -- it's likely that that's against the license. I see two possibilities Documenting the dependency Using a #pragma in your .h file that requests the .lib to be linked against. If VS can find it, it's the same as including it ...
5,445,070
5,445,096
How does the C++ runtime system know when objects go out of scope
I was wondering how the C++ runtime system detects when an object goes out of scope so that it calls the destructor accordingly to free up the occupied memory. Thanks.
This is known statically at compile time { string s; /* ctor called here */ } /* dtor called here */ Sometimes, it's more difficult { again: { string s; /* ctor called here */ goto again; /* now dtor of s is called here */ string q; /* ctor not called. not reached. */ } /* dtor of s and q would be ...
5,445,105
5,445,220
Conversion from void* to the pointer of the base class
I have some hierarchy: base, derived classes and some structure storing user data as void*. That void can store both Base and Derived classes pointers. Main problem that I do not know what is stored there base or derived pointer. class Base { public: int type; }; class Derived: public Base {}; Base* base;//init bas...
void*'s can only be converted back to their original type. When you store a Derived* in a void*, you can only cast back to Derived*, not Base*. This is especially noticeable with multiple inheritance, as your derived object might not necessarily be at the same address as your base. If you really need to store things (a...
5,445,186
5,445,228
boost::spirit example doesn't compile
I was following the tutorials in the Spirit documentation, and I'm stuck here: #include <iostream> #include <string> #include <boost/spirit/include/qi.hpp> template <typename Iterator> bool parse_numbers(Iterator first, Iterator last, double &sum) { namespace qi = boost::spirit::qi; namespace ascii = boost::spirit::as...
Add this: #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_operator.hpp> to your includes and it should work.
5,445,299
5,445,367
Ambiguous type reference
Why does this works : template <typename T> struct foo { }; struct A { typedef foo<A> type; }; struct B : public A { typedef foo<B> type; }; int main() { B::type john; return 0; } But not this : template <typename T> struct foo { }; template <typename T> struct Shared { typedef foo<T> type; }...
Because B inherits foo<B> and, indirectly, foo<A>, and both contain a member type. Which did you mean? Your simple, first piece of code has B's type hiding A's type, but that doesn't happen in the more complex second piece of code, which involves a deeper inheritance tree.
5,445,341
5,445,445
What is the ideal memory block size to use when copying?
I am currently using 100 megabytes per memory block to copy large files. Is there a "good" amount that people normally use? Edit Thanks for all the great responses. I'm still quite new to these concepts so I'll try to understand a lot of the ones that have been said (e.g. write back cache). I keep learning new things :...
A block between 4096 and 32KB is the typical choice. Using 100MB is counter-productive. You are occupying RAM with the buffer that can be put to much better use as the file system writeback cache. Copying files is very fast when the file fits completely in the cache, the WriteFile() call is a simple memory-to-memory ...
5,445,476
5,445,508
.get function with an opened file stream in C++
I have an open input file stream. It is able to open the other file (a txt file) successfully. And by making adjustments to the code right below I can get it read and output the other txt file (all ASCII characters, just letters) just fine. However, I was playing around with the below function. This results in one line...
In the first version the .get(array,size) extracts characters until the delimiting characters. By default this is a newline, '\n'. However once reaches this character, it does not extract it from the input stream but leaves it for the next input attempt. Therefore the next time you call get() it will find the newline f...
5,445,492
5,445,524
delete dynamically allocated object from std::vector
Is this correct?: std::vector<Enemy*> enemies; enemies.push_back(new Enemy()); Enemy* enemy = enemies[0]; enemies.erase(enemies.begin() + 0); delete enemy;
It works, yes, but it's not an ideal approach. Firstly, adding 0 is just noise, you can remove that. But even better, just use pop_front(). Also, no need for the intermediate step, you can delete before removing. But std::vector isn't good as popping from the front, especially if it's large (because the remaining eleme...
5,445,606
5,445,854
Cannot upload a file to a ftp server using C++
I have this simple code to upload a file to a server, but it seems that it doesnt work, doesn't upload any file(FtpPutFile returns 0). I am using FileZilla Server and this is my code and what FileZilla says: void upload() { hInternet = InternetOpen(NULL, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0); hFtpSession = ...
With GetLastError() returning ERROR_SHARING_VIOLATION (32) for FtpPutFile, it likely means that that there is an open handle to "c:\stories.txt" that prevents read sharing. If you have this file open in your program, you will need to either allow read sharing in the CreateFile call or close all open handles that preve...
5,445,617
5,446,704
Removing rows from QAbstractTableModel derived class don't work, why?
I have a Qt application for which I derived my own model class from QAbstractTableModel. I have implemented the necessary methods as prescribed in the documentation. When I call removeRows method the changes are correct in my View (the rows I wanted to remove are removed). But somehow, the operations on the model doe...
It turns out that nothing was wrong with my implementation of removeRows. The save method was called by my unit tests just before showing my dialog. The dialog was not calling the save method at all. No wonder the change were visible in the View and not in the output file...
5,445,638
5,445,677
Tutorial for Topdown 3D
Well, i'm looking for a good guide to program Topdown 3D in C++. Where i can find a good one? Thanks.
Topdown isn't any different than any other 3D programming - except for the position of the viewer. You can get some more information about what you want to do by checking out gluLookAt() Your "up" would be X or Z depending on what you wanted to do and if you still wanted to use right-handed coordinates for everything e...
5,445,752
5,445,839
DLL-based application framework with bi-directional interfaces (Windows)
Solved this wasn't the problem, since it's being implicitly cast to IFramework anyway. I was concerned it may have to do with my methods not returning HRESULT, or with my stubby implementations of IUnknown::QueryInterface, but the real problem was merely a compiler setting that had overridden several macros I needed fo...
If you want to allow different compilers for the plug-ins from what you use for the app then you need to use COM exclusively across the boundary between app and plug-ins. That is precisely the problem that COM was designed to solve.
5,446,005
5,446,076
Why don't static member variables play well with the ternary operator?
Here's the deal. I have a static class which contains several static functions used for getting input. The class contains a private static member variable for indicating whether the user entered any information. Each input method checks to see whether the user entered any information, and sets the status variable accor...
This is according to the C++ Standard. The ternary operator does constitute a single lvalue that will refer to either GOOD or BAD at runtime. The lvalue to rvalue conversion is not applied immediately to either the lvalue GOOD or BAD, and therefor you require a definition of GOOD and BAD. See the core language issue r...
5,446,161
5,446,172
Reading piped input with C++
I am using the following code: #include <iostream> using namespace std; int main(int argc, char **argv) { string lineInput = " "; while(lineInput.length()>0) { cin >> lineInput; cout << lineInput; } return 0; } With the following command: echo "Hello" | test.exe This result is an infin...
string lineInput; while (cin >> lineInput) { cout << lineInput; } If you really want full lines, use: string lineInput; while (getline(cin,lineInput)) { cout << lineInput; }
5,446,319
5,446,359
Recursivly make .O files with g++?
I have my main.cpp file, and in that folder is another folder called src, and in that folder are more folders etc... How could I compile this easily with g++? I do not want to make a make file at this time because I'm still working on my project but I want to test in in Linux and OSX. Thanks
You could do it the right way, with a Makefile, or by making a list every time you build, something like: g++ -Wall -o myapp `find . -name \*.cpp`
5,446,446
5,446,471
GLSL: Changes in uniforms not rendered
I'm tweaking the shader examples in OpenGL Superbible 2010 to learn about shader usage. I wanna change the red component of a directional light that's passed as a uniform to a diffuse light shader. The vector GLfloat vDiffuseColor [] = {redDirectionalLight, greenDirectionalLight, blueDirectionalLight, 1.0f}; is defin...
Please tell me you're changing vDiffuseColor and not redDirectionalLight, greenDirectionalLight, blueDirectionalLight. GLfloat vDiffuseColor [] = {redDirectionalLight, greenDirectionalLight, blueDirectionalLight, 1.0f}; makes an array by copying the initializer, there is no connection to the original three variables. ...
5,446,498
5,446,505
Will istream::get() with no parameters return whitespace?
This seems like a really simple question, but I can't find the answer anywhere. If I'm parsing a file (that includes newline characters) character by character, using char next = file.get(); will the following check ever be true? if (next == '\n')
Yes. It gets the next character from the stream. It does not skip newlines or whitespace.
5,446,767
5,446,782
Casting double pointers of base classes
I have an Abstract class, say Animal. From this class, I have many inheriting classes, such as Cat, Dog, Mouse. I have a method that I want to be able to take pointers to pointers of these objects. So void someMethod(Animal **anAnimal); How is this accomplished? It seems I am not able to cast upwards like this. I ...
You need an Animal*: Dog* d = new Dog(x); Animal* a = d; Animal** animal = &a; someMethod(animal); An Animal** can only point to an Animal*. It would be very bad if it could point to a Dog*. If it could, you could do something like this: Dog* d = new Dog(x); Animal** animal = &d; *animal = new Hippopotamus(); Now d...
5,446,788
5,446,814
Difference between \015 & \012 and \r & \n
I have an old C++ program that is writing files and FTPing them to a IBM mainframe. This program is being converted to C#. Things seems OK in transferring but the mainframe viewer is not displaying the file properly. What is the difference between \015 & \012 and \r & \n? C++ is using the numbers and C# is using \r\...
\015 is an octal literal, which C# does not support. C# parses it as \0 (character code zero) followed by the two characters 15
5,446,827
5,446,947
C++ Recognizing double digits using strings
Sorry, I realized that I put in all of my code in this question. All of my code equals most of the answer for this particular problem for other students, which was idiotic. Here's the basic gist of the problem I put: I needed to recognize single digit numbers in a regular mathematical expression (such as 5 + 6) as wel...
First, it helps to move such ifs like this userInput[i] != '+' || userInput[i] != '-' || userInput[i] != '*' || userInput[i] != '/' || userInput[i] != '^' || userInput[i] != ' ' && i < userInput.length() into its own function, just for the clarity. bool isOperator(char c){ return c == '+' || c == '-' || c == '*' |...
5,446,850
5,447,078
Make Apache read PHP documents from RAM / Memory?
Is there any way to make Apache to read PHP documents from RAM? I'm thinking of creating a virtual disk in the memory and then modify httpd.conf to change the document root directory to the virtual disk in the memory. Is this viable? Basically, what I want to do is distribute my PHP code to my users' computers so they ...
You can, in theory, have Apache serve files out of a Samba share. You would need to configure the server to mount a specific file share made by the user. This won't work if the user is behind a firewall or NAT gateway of any variety. This will be: Slower than molasses in January ... in Alaska. Apache does a lot of ...
5,446,958
5,448,999
How to link to debug versions of binary libs
If I pass a lib name with -l option, then GCC will link to the best lib from /usr/lib. I think the dynamic version is chosen over the static version when both are present. But there are also debug versions of the same lib. Debug versions are supposed to be compiled with optimisations off and extra runtime checks on. I...
If you are aware of the name of the debug library, you can directly use it in compilation instead of going with -l option. For example : gcc -o <output_file> *.c <libdebug_file>.so
5,447,002
5,447,085
How to read a birthday with symbols "/" and ":" from a .txt file?
I am writing a c++ prgram and have to read some data from a .txt file.the format looks like the following: "name gender DD/MM/YYYY HH:MM:SS" I know how to read a .txt file and cin the words one by one, but i dont know how to deal with the symbols "/" or ":". I have to compare the ages of two person. Please help!
Aside from the easiest way with sscanf, like Jerry describes, it's also possible with iostreams. Just read the data you want from the file, until you hit a seperator, and discard that one into a dummy char: char dummy; myfile >> first_name >> last_name >> day >> dummy >> month >> dummy ... // and so on.
5,447,316
5,447,328
Convert long to char* const
What is the right way to convert long to char* const in C++? EDIT: long l = pthread_self(); ThirdPartyFunction("Thread_Id_"+l); //Need to do this ThirdPartyFunction(char* const identifierString) {}
EDIT: The "proper" way to convert an integer to a string, in C++, is to use a stringstream. For instance: #include <sstream> std::ostringstream oss; oss << "Thread_Id_" << l; ThirdPartyFunction(oss.str().c_str()); Now, that probably won't be the "fastest" way (streams have some overhead), but it's simple, readable, a...
5,447,397
5,447,434
Find number of levels from one node to another
I'm trying to write a function that will return the number of levels from one node to the other in a quad tree. Here's what I have so far, but I'm sure it's incorrect, I just cant figure out why: int levels(QtreeNode * orig, QtreeNode * n) { //calculates the number of levels from orig to n if(orig==n) ...
your mistake is that you add levels on path to dead end's, but you need to calc way linked that two nodes int levels(QtreeNode * orig, QtreeNode * n) { int path; // found! if (orig == n) return 0; // it's dead end, do not calc that way if (orig->isLeaf()) return -1; path = level...
5,447,508
5,447,526
Why can't I have these two overloads in a class?
In the code below, if I comment out aaa or bbb it will compile. Why can't I have both? #include <iostream> class MyClass { private: typedef void (MyClass::*aaa)() const; typedef void (MyClass::*bbb)() const; void ThisTypeDoesNotSupportComparisons() const {} public: operator aaa() const { return (true) ...
Your typedefs for aaa and bbb are identical. So your conversion operators are actually declaring the same function. Essentially, the compiler sees operator void (MyClass::*)() const { ... } twice, once for aaa, and once for bbb.
5,447,576
5,454,288
invalid conversion from time_t to const time_t*
time_t raw_time = time(NULL); tm* current_time = localtime(&raw_time); I got the answer myself... I totally messed up the warnings. Thanks anyway.
localtime requires an argument of "time_t*" which is a pointer. So you have to put the & there.
5,447,635
5,447,709
vc++ - socket is not writing into the port
I am trying to create a ftp client with uploading a file capability. But the socket is not sending the message into the server, even though it got the connection with the server. See the code below #include <iostream> #include <string> #include <tchar.h> #include <Winsock2.h> #include <winsock2.h> #include <ws2tcpip.h...
FTP commands are terminated by a carriage return - line feed pair (\r\n). You need to add \r\n to your USER command string. Edit: you should consult RFC 959 for more information (there's more FTP-related RFCs that update and extend RFC 959 too). It has a section detailing the base FTP commands and shows the expected ...
5,447,675
5,447,776
How to convert a string to a class name
Possible Duplicate: C++: instantiate class from name? For example, if I have string s = "myObject"; So how can I use that String s to make this one? return new myObject(); I tried this one but it's quite silly and it's wrong return new s(); Thank you
You can create a simple factory and register the classes you want to be able to construct. This is a very light-weight sort-of reflection. #include <map> #include <string> template <class T> void* constructor() { return (void*)new T(); } struct factory { typedef void*(*constructor_t)(); typedef std::map<std::st...
5,447,752
5,447,781
How to read predefined (#define) across projects?
I have 2 projects in the same solution: A is static library and B is exe. B depends on A In B I do a declaration for a DEBUG mode. Something like #define DEBUG Then I went to check if DEBUG is defined in A, if it does then do some debug printing: // Code in A #ifdef DEBUG cout<<"debug message"; #endif But this doesn't...
The usual solution is to build two A's, one for Debug and one for non-debug. Then the other projects can choose which one to link against.
5,447,864
5,447,889
string tokenizer in c++
Hello I have a code that is char * cip = "192.168.0.1\t\t78.90.56.4"; I want to convert it to char * ip1= "192.168.0.1"; char * ip2 = "78.90.56.4"; I have done ip1= strtok(cip, "\t\t "); I don't know how to get the second ip I don't know how to do this using string tokenizer. kindly help me thanks
Try this function: ip2 = strtok(NULL, "\t\t");
5,447,907
13,347,401
Programmatically counting cache faults
I need to evaluate the time taken by a C++ function in a bunch of hypothesis about memory hierarchy efficiency (e.g: time taken when we have a cache miss, a cache hit or page fault when reading a portion of an array), so I'd like to have some libraries that let me count the cache miss / page faults in order to be capab...
It looks like now there is exactly what I was searching for: perf_event_open. It lets you do interesting things like initializing/enabling/disabling some performance counters for subsequently fetching their values through an uniform and intuitive API (it gives you a special file descriptor which hosts a struct containi...
5,447,934
5,447,991
Why is this operator called in C++?
I dont understand, why is the aaa operator called in the 2nd last line? #include <iostream> class MyClass { private: typedef void (MyClass::*aaa)() const; void ThisTypeDoesNotSupportComparisons() const {} public: operator aaa() const { return (true) ? &MyClass::ThisTypeDoesNotSupportComparisons : 0; } }; ...
The compiler searches for the best match for (a && b). Because the class doesn't have an operator that turns MyClass to a boolean, it searches for the best cast. operator aaa() const is a cast to an aaa type pointer. Pointers can be evaluated in an if sentence. Overloading typecasts Conversion Functions (C++)