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
7,361,327
7,361,717
Getting parts of a file path
I have a file path, gotten from the __FILE__ macro, and I want to extract 2 pieces from it. The format is: /some/path/to/a/file/AAA/xxx/BBB.cc. I want the AAA and BBB path. xxx is generally src, inc, tst, etc, and the file extension is generally .cc, but not guaranteed. I know I can use string.find() or even splitting...
Use rfind, so that you can start at the end and work backwards: string s = "/some/path/to/a/file/AAA/xxx/BBB.cc"; unsigned int a = s.rfind('.'); unsigned int b = s.rfind('/'); string BBB = s.substr(b+1,a-b-1); a = s.rfind('/',b-1); b = s.rfind('/',a-1); string AAA = s.substr(b+1,a-b-1);
7,361,417
7,361,443
Function returns char *
Is it correct to write a function that returns char *? Something like this: char * func() { char *c = new char[3]; strcpy(c, "hi"); c[2] = '\0'; return c; } int main() { char *c; c = func(); //code using c delete [] c; return 1; } It works, but is it correct?
It is correct (assuming you meant strcpy and not strlen), but it must be very clear from the documentation of the function that it's the caller's responsibility to free the returned pointer, and what method does it have to use to free it (new => delete, new [] => delete[], malloc => free, etc). That is the "C way" of d...
7,361,505
7,361,525
random number generator related question
So here's the code: if(rand_s(&number) != 0) cout << "Random number generator failed!" << endl; Question is - does it mean that the program outputs a failure message every time the random number generated with this rand_s(&number) expression is greater than zero? And if so, why would i want such a thing? // complete c...
No rand_s returns an errno_t so 0 means there was no error. Anything else is indicating that there was an error when running the function. More information can be found here
7,361,547
7,361,552
I wonder what really the &a returns?
Suppose First case int a; int *p= &a ; it works no error Second case long int a; long int b; b = & a; it wont work Most of us say b is a variable not a pointer. But see the below. So the question is if the &a returns the address which is an unsigned integer then why cant we assign it to a normal variable? But ...
Integers, even long int, are not always going to be the same size as a pointer. Sometimes they will be (for example, most 32-bit architectures have sizeof(int) == sizeof(void *)), sometimes they will be different (for example, some 64-bit architectures have sizeof(long) == sizeof(void *) but some do not -- Visual C++ o...
7,361,626
7,361,689
Why does this class freeze the program?
This class should read some lines from a data and from them to variables which i can use in further operations. but for some reason it freezes if it detected the data and try to load it. why? i can't see my mistake hope u can help me. btw: the strange language which is used in the class is german^^ hope this doesn't ma...
What I see in your loop is, that you don't read any line if you are not at the line you want to be at. But as you don't read any line, you will not get further to the line you want to read. That does not only prevent you from reaching the line you actually want to read, but also from reaching the eof in acceptable time...
7,361,736
7,461,166
how to turn C++/CLI .Net socket into boost::asio socket?
What I want is simple - code sample of creating new boost asio socket from C++/CLI .Net socket. How to create such thing? Here is pseudo code of what I would like to do: .net::socket a; boost::asio::socket b; b.assign(a.nativeWin32Socket());
Have you tried? b.assign(a.Handle.ToInt32()); Also note they you will need to use WSADuplicateSocket as you may get that both b and a will close the socket and point you don't expect. So you need something like: SOCKET native = WSADuplicateSocket(a.Handle.ToInt32(),...); b.assign(native); Full Answer (Tested) SOCK...
7,361,934
7,362,011
How to display c++ output message in windows R
My R function is calling a c++ code which will "cout" some lines during its iterations, I can see this lines in windows R called by Command Prompt. But I could not see anything when I directly open R in windows os. I wonder is there any way to see the c++ output from R under windows but not in command prompt? Or if n...
See the Printing section of Writing R Extensions. You want Rprintf.
7,361,944
7,429,225
Saving state of complex, scripted objects
In C++ I have the following two classes that I expose (using Boost) to Python: struct Foo { // Empty }; struct FooContainer { // I use boost::shared_ptr for compatibility with Boost.Python vector<boost::shared_ptr<Foo>> foos_; }; In the Python side I might create a special type of Foo that actually does s...
You can use boost::python/pickle, and save the data from python. I only have limited experience with the pickling suite, but it should work provided you override appropriate pickling methods in your classes derived in python (see my answer to this question).
7,362,154
7,362,456
How can I use OpenCL in my system
I have a laptop running Ubuntu, it has a 32 Bits processor (Intel Core 2 Duo T6400 2.00GHz) and a graphics card Intel Corporation Mobile 4 Series Chipset Integrated Graphics Controller. I would like to know if I can program with OpenCL in this system. If yes what do I need? I have been searching Google, ofcourse. I fou...
Unfortunately you will need the following distributions: http://software.intel.com/en-us/articles/opencl-release-notes/ Novell* SUSE* Linux Enterprise Server 11 Service Pack 1 (64-bit version) Red Hat* Enterprise Linux 6 (64-bit version). If you cannot change distribution, an alternate way is to use NVIDIA's CUDA SDK i...
7,362,172
7,362,369
OpenCV: "Feature Matching with FLANN" tutorial - getting exception
I am starting up with OpenCV (using C++) and was playing around with the "Feature matching with FLANN" tutorial from here: http://opencv.itseez.com/doc/tutorials/features2d/feature_flann_matcher/feature_flann_matcher.html I did not modify anything, just tried running it as it is. Unfortunately, when running it, I am ge...
It sure helps to know more about C++ than a worm :) I realized I had linked against the release version of the feature2d lib. As always, solved automatically by virtue of the "power of posting"...
7,362,325
7,364,133
c++ openGL picking problems
I'm working on a little example, where I have loaded an object from a wavefront file - and am trying to get my picking right, I've gone over this and a few tutorials about 10 times... but must be missing something. Was wondering if anyone could provide an extra set of eyes. I've used a saved list to draw the object, wh...
A few things to consider here: OpenGL selection mode is deprecated and never was HW accelerated, except on a few SGI boxes and 3DLabs GPUs. DisplayLists don't mix with Vertex Arrays. Why do you call glutSwapBuffers right before drawing your list of saved objects? Makes absolutely no sense at all.
7,362,607
7,362,674
where can i find source code for libcrypto++?
I am using libcrypto++ for aes encryption. I would like to add in my code the methods: EVP_CipherInit_ex(), EVP_CipherUpdate(), EVP_CipherFinal_ex(). Where can I find this source codes? thx. appreciate
Here you go: http://www.openssl.org/source/ The downloadable tar.gz on the page contains both header and source files for the most common cryptography algorithms, including EVP However, I believe you are misunderstanding what static linking means, and how it is different from dynamic linking. Here is a decent article: ...
7,362,723
7,362,915
Time based loop and Frame based loop
Trying to understand the concepts of setting constant speed on game loop. My head hurts. I read the deWiTTERS page, but I can't see the why/how...when I get it...it slips. while(true) { player->update() ; player->draw() ; } This will run as fast as possible depending on how fast a processor is...I get that...
In cases where the update_game() and display_game() functions complete in less time than a single frame interval at 60FPs, the loop tries to ensure that the next frame is not processed until that interval is up, by sleeping (blocking the thread) off the excess frame time. Seems like it is trying to ensure that the fra...
7,362,725
7,362,792
Calculating using only the first 3 decimal digits, how?? (c++)
We have a school assignment and we were told that all numbers end after the third decimal digit, meaning 0.0009 is 0 in our case. How can I do that in c++? Should I create a new class using operator overloading? Thanks
Should I create a new class using operator overloading? That would help make the code that uses the class simple. It's up to you to decide whether you want to make the effort to obtain that simplicity. How can I do that in c++? In C++ there is a way to truncate a floating point number to zero decimal places: a cast...
7,362,748
7,365,294
About Xcode4 and C++
Since I have Xcode4, I can't use the refactoring capabilities of XCode with C++ project. Is there a way around that or does the only language Xcode cares about is Object C ? Thanks.
Xcode's refactoring tools currently support only C and Objective-C. They don't support C++.
7,362,866
7,363,070
GetStartupInfo() differs according to the explorer the app is launching from
I have a C++ app that launches another one with CreateProcess(). I fill the STARTUPINFO data with GetStartupInfo() before. Here is the code: STARTUPINFOA si; PROCESS_INFORMATION pi; GetStartupInfoA( &si ); cout << si.dwFlags << endl; cout << si.hStdError << endl; cout << si.hStdInput << endl; cout << si.hStdOutput <<...
The STARTUPINFO record you receive comes from the CreateProcess call that started your program. Two different and completely independent programs called CreateProcess, and they evidently chose to populate the STARTUPINFO record differently. Nothing remarkable about that. Incidentally, unless dwFlags includes STARTF_USE...
7,362,983
7,363,031
Specification for the type in a class using templates (instead of inheritance)
When inheriting from a class, you know the requirements and restrictions imposed on you by simply looking up the hierarchy. For example, you can find out just by looking at the parent class(es) which methods are required to be defined (pure virtual). If one chooses to use templates instead (if it fits the bill) then th...
You're essentially describing the kind of problem that C++0x concepts was going to solve by providing programmers a way to enforce requirements on type at compile time. However, it was removed in July 2009 due to time constraints. There is a library-only solution in Boost called the Concept Check Library (BCCL). Howeve...
7,363,257
7,363,299
counting characters in char array
i wrote following code to count occurance of characters in given char array #include <iostream> #include <string> using namespace std; int main(){ char f[]={'a','a','b','c','c','d','d','f','e','e'}; int n=sizeof(f)/sizeof(char); char max=f[0]; for (int i=1;i<n;i++) { if(f[i]>max) { max=f[i]; } } i...
You have to initalize the "malloc"ed (new) area to 0, it contains garbage.
7,363,410
7,363,458
How to debug C++ memory errors?
Does valgrind work with STL allocator? I am using STL vector with plain C library in the follwing fashion: double some_C_functions(int, double*); std::vector<double> v; ..... double result = some_C_functions(v.size(), &v[0]); What if the C functions tries to overshoot the pointer? Can valgrind detect the error?
Valgrind should still be able to detect that since it's hooking into the memory management which still goes to the same heap for C or C++. Obviously it's hard(er) to detect errant reads though.
7,363,571
7,363,642
Returning multiple values and default parameters in C++
I'm trying to make a function that takes in either 1 or 3 parameters, and returns either 1 or 3 values (based on parameters passed). If 1 parameter is passed then the function uses default values for the other 2 arguments. If 3 parameters are passed then it uses those values. bool foo( bool x, int &y = 0, int &z = 0) {...
You can do it with two functions: bool foo( bool x, int &y, int &z) { x = true; // this isn't really what it does, is it? y = y + 1; z = z + 2; return x; } bool foo(bool x) { int a = 0, b = 0; return foo(x,a,b); }
7,363,760
7,363,806
Can't figure out error
I'm trying to get google glog to work with windows, but I get these errors that I can't figure out. // Variables of type LogSeverity are widely taken to lie in the range // [0, NUM_SEVERITIES-1]. Be careful to preserve this assumption if // you ever need to change their values or add a new severity. typedef int LogSev...
The mistake should be somewhere else, maybe in a previous header? The code you posted compiles without problems: http://ideone.com/Wf64q
7,363,774
7,363,929
C++ Converting binary data to a hex string and back
I have a matching pair of static functions in a utility class that I use to convert between binary data (unsigned characters) and it's string representation (a-f and 0-9). They seemed to work correctly but recently I tried to compile my code under Visual C++ (2010 Express) and to my dismay, they cause nothing but heap ...
In this code, for(unsigned int b = 0; b < effective_length; b++) { sscanf(source.data() + (b * 2), "%02x", (unsigned int*) &destination[b]); } you seem to be writing an unsigned int at locations destination, destination+1, destination+2, &c. As you approach the final bytes of your destination buffer, you will wri...
7,363,790
7,363,857
Compiler optimizations of inlined functions in C++
When a function which take a pointer in argument is inlined, does the compiler remove the indirection during the optimization process ? Of course when it makes sense.. Here is an obvious example: inline void say_hello (person* p) { std::cout << "hello " << p->name << std::endl; } int main () { person goldorak;...
I'm assuming GCC, and so the link you are looking for is http://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html And to quote: (this may not be what you were getting at) -findirect-inlining Inline also indirect calls that are discovered to be known at compile time thanks to previous inlining. This option has a...
7,363,792
7,363,807
Created the same Program in Unix and Visual Studio 2010, the Visual Studio one wont compile
We are using Emacs on Sun OS 5.9. I wrote the exact same code in both emacs and visual studio and put them in their own folders on the unix server. The one from emacs compiled without a problem but the one from visual studio wont. I opened the visual studio version in emacs and it looks just like the one i created in e...
return 0: The error is right there. return 0; with ;
7,363,800
7,365,045
unary minus overload: member or non-member?
Given that prefix unary operators can be "implemented by a non-static member function with no parameters or a non-member function with one parameter" (§13.5.1[over.unary]/1), is there a difference besides the usual encapsulation/code reuse design rationales that apply to any member/non-member function choices? For bina...
As far as I'm aware there are no differences as compared to deciding if a non-operator function should be member or non-member. Obviously prefer non-member, non-friend when possible (like the standard algorithms).
7,363,861
7,364,740
Passing a std::unique_ptr as a parameter to a function
I got a structure and a function like the following: struct MYOVERLAPPED : public OVERLAPPED { //... }; void func1(std::unique_ptr<MYOVERLAPPED> pBuf) { //... }; I am obtaining a pointer to MYOVERLAPPED which i want to pass to the func1-function. The problem i encounter is, that no matter what i try i get th...
While you cannot convert from std::unique_ptr<base> to std::unique_ptr<derived> directly, it is not too hard to write a cast function that will be safe (i.e. not leak the resource under any circumstance, and only succeed if the cast is valid: template <typename Dst, typename Src> std::unique_ptr<Dst> unique_dynamic_cas...
7,364,132
7,364,198
What type of Visual Studio c++ project should i select for making basic unix apps
Im in a computer science 1 class and we are programing using C++. In class we use emacs on unix servers. We can also use visual studio if we want. If its going to be graded in emacs and run there by the professor what type of project should i pick in Visual studio for the best results. every time i try to compile the c...
I strongly suggest you just use emacs and unix. Ubuntu Linux is free, emacs is free, and g++ is free (c++ compiler). It's best to always use the same platform your professors are using. If you have to use Visual Studio for some reason, you can do a console application project, but you are going to have all kinds of ...
7,364,604
7,364,627
new double[x] vs vector<double> (x) where integer x is user specified
Suppose in a code I want the user to specify an integer(say x) and then allocate those many consecutive cells in computer memory on which I do some kind of processing. My question is is it "better" to allocate this memory as new double[x] or vector<double>(x). I know that both methods seem to work fine ( i.e. compiles...
It's better to use vector whenever you can because of the many advantages it provides (automatic memory management, bounds checking, etc). Also, to have the vector reserve a number of elements for you to use (i.e. allocate that many all at once in memory instead of eventually resizing up to it as you add elements), you...
7,365,065
7,365,173
Pointers to Pointers to Pointers (Error: Expression must have classtype)
I'm having some trouble with multi-layer pointers. Basically I'm reading point locations from a file and using them to map out polylines. I'm trying to create a dynamically allocated data structure that will change depending on the information contained in the file. Each file is structured like this. 29 // number of po...
You've got a triple-layered pointer. You need three de-references in there. You've only got two with dinoPoints[j][i]- the result of that expression is a pointer. Not to mention the horrendous unsafety of what you're doing. Use a vector<vector<vector<coordinates>>> for this- it's safer and easier to understand.
7,365,107
7,365,154
How can I debug into an Intel C++ library from managed code?
I've got a C#/NUnit test calling into a C++ library compiled using the Intel C++ compiler (version 12, I beleive). I've got the PDB, disabled 'Just My Code', enabled Unmanaged Code Debugging. Still, ordinary debugging doesn't work - it says it hasn't got the sources and offers to show disassemly. In addition: I'm const...
The PDB file needs to be in the same directory that the assembly is loaded out of. NUnit copies the test dll to a temp directory and loads it from there -- did it copy the PDB. One way to check is to use ProcMon (which can show all file accesses) and filter for PDB files to see where it's trying to load it from. Pr...
7,365,333
7,365,356
Overloaded typecasts don't work
I've built a little class representing a decimal number, called Complex. I want to be able to cast it to double, so here's my code Complex.h public: operator double(); Complext.cpp Complex::operator double() { return _num; } _num is a field of type double of course That seems to be okay. The problem is in anothe...
You need to make your operator double a const function: operator double() const; and Complex::operator double() const { return _num; }
7,365,448
7,365,770
Pre-compiled header gets created on every make?
I have a very simple makefile, that basically does the following: # Pre-compiled header CORE_PCH_FILENAME =Core.h CORE_PCH: $(CXX) $(CXX_CFLAGS) -x c++-header $(CORE_PCH_FILENAME) #Objects obj/%.o: CORE_PCH %.cpp obj/%.d @mkdir -p obj $(CXX) $(CXX_CFLAGS) -c $*.cpp -o $@ #Dependencies obj/%...
The problem is that you do not refer to the gch by name, and there is no file named CORE_PCH, literally. Try: CORE_PCH_FILENAME=Core.h CORE_PCH=$(CORE_PCH_FILENAME).gch $(CORE_PCH): $(CXX) $(CXX_CFLAGS) -x c++-header $(CORE_PCH_FILENAME)
7,365,518
7,365,636
Color coding emacs being accessed remotely with putty
I use PuTTY to log on to my university's unix server and then start emacs and code in that. is there anyway to color code the code. Its C++ and ive been doing research for 2 hours and found nothing
The first step is to do a M-x font-lock-mode and see if that works. You also might be running into a problem with the terminal emulation colors, as emacs does font-locking (coloring) of code pretty much automatically now. Try running emacs with --color=always and see if that gives you color.
7,365,570
7,365,761
Register non-static C++ methods in Lua
I'm trying to make a small C++/Lua system where I would create my objects and attach behaviors to them in Lua. Right now I'm using LuaWrapper (a small header with basic C++ to Lua stuff), my problem is that as far as I can see Lua only let me register static class methods (or non-static functions), a little research an...
LuaWrapper isn't meant to hook up directly to non-static functions in a class. I suppose it could be with some special trickery, but this is how I designed it to be used: static int Widget_AddChild(lua_State* L) { Widget* parent = luaW_check<Widget>(L, 1); Widget* child = luaW_check<Widget>(L, 2); if (paren...
7,365,809
7,395,863
Event Callback Daemon
I am working on an event daemon in C++ that I would like to use member function callbacks. Basically an event queue would collect events which the daemon continuously services. There is a base class Event struct with an ID and all events would derive from it. I would like the methods registered for each event to use th...
Okay, so I finished an implementation of my original desired interface. I was looking through Dennis' answer but eventually got lead to functors and I realized what I was looking for was a simple polymorphic solution. I failed to grasp before that I could create a non-templated base class with which to use for storing ...
7,366,043
7,366,072
char string length and memory leak
int fCount = 0; char frameNum[7]; sprintf(frameNum, %06u", fCount); int fCount = 0; char frameNum[6]; sprintf(frameNum, %06u", fCount); Q1. Which is correct, 6 or 7? Q2. I am using VC6 and the file is sample.cpp. I think sprintf is C. Is there a better way? I need the char string right justified and with padded...
First one is correct. There is no memory leak, by the way. -- I think sprintf is C. Is there a better way? Yes. C++ way: std::stringstream ss; //#include <sstream> ss << fCount; std::string frameNum = ss.str();
7,366,289
7,367,527
Is it good to put version information into environment variables for include paths to third party libraries?
When you are setting up a project to compile in C++, be it VS or make, what is the best practice for setting up environment variables which are used in include paths for third party libraries? Do you include the version number in the variable? i.e. THIRD_PARTY_LIB_3_1_1=c:\libraries\thirdparty\3.1.1 and then have $(THI...
It depends. You should think about it in terms of how the build system would use that information to change its behavior. It won't act any differently whether you name it one or the other, then its just making more work (and possibly confusion) for yourself. If a single build needs to include multiple versions of th...
7,366,458
7,366,507
C++ checking enum flags
In one of my classes, I have an integer that stores a set of enum flags like so: enum AttackFlags { Contact = 1, //Move connects with target Projectile = 2, //Attack is projectile based Unblockable = 4, //Attack can not be blocked Unc...
I am not sure I am following your question, because you seem to mention the obvious solution. So what is wrong with this as a solution, obviously add whatever additional flags you wish: bool HasAttackFlags(int flags) { return (flags&(contact|projectile))!=0; } EDIT: Oh... I think I just figured it out, do you want...
7,366,508
7,366,735
Open a std::vector<int> in Excel from memory heap without serializing?
If I have a vector of int in memory, is there a way to pass this to Excel? Currently the only way I know is to write the data to file as a csv, then pass the saved file to excel to execute.
Actually the only direct connection would be using a DDE link. Now I don't usually recommend that, as it is a bit of an aged technology, it sure fits the description about right, so I thought I'd mention it. I've seen in used for real-time trading systems in international dealing rooms. However, keep in mind that Excel...
7,366,638
7,367,371
Phonon can read .avi files on MacOS?
I try to read a .avi file on MacOS X with Phonon and Qt. But I can't. Even in QtDemo, the "Media Player" is not able to display those kind of file. Is there a way to make it work ?
Try installing the right codecs to the system. "avi" is actually just a container file format that can contain media encoded with many possible audio and video codecs, that might not be supported/installed by default in OS-X. Phonon itself doesn't provide media decoding capabilities, it uses whatever is available on th...
7,367,446
7,367,526
Question on Infinte Loop in C++
This is kind of a curiosity. I'm studying C++. I was asked to reproduce an infinite loop, for example one that prints a series of powers: #include <iostream> int main() { int powerOfTwo = 1; while (true) { powerOfTwo *= 2; cout << powerOfTwo << endl; } } The result kinda troubled me....
In Python, integers can hold an arbitrary number of digits. C++ does not work this way, its integers only have a limited precision (normally 32 bits, but this depends on the platform). Multiplication by 2 is implemented by bitwise shifting an integer one bit to the left. What is happening is that you initially have onl...
7,367,675
7,368,682
delete dynamically allocated memory in openGL
I use C++ and and freeglut, and want to know how to delete the dynamically allocated memory using new. I need to free the memory when closing the window. Where should I put this delete pointer? before glutMainLoop()? *Update*. For example, I use int *ptr = new int[n] to store the vertex coordinates, and did not use c...
The old form of GLUT made it so that your program's execution never returned from the call to glutMainLoop. FreeGLUT gets rid of this, but only if you specifically ask for it before calling glutMainLoop: glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION); This means that, when you eventually ca...
7,367,872
7,367,930
Linker not recognizing some #includes?
I have a VC++ solution with multiple projects and multiple namespaces. Each project has its own namespace, and some projects have multiple namespaces. Sometimes, when I reference an object from another project I will end up with "unresolved external symbol" errors even though I #included the header file and referenced ...
If you are using Visual C++, Go to your project properties, under Linker > Input, you should add the compiled .lib file of the project you are depending on. Like others have stated, the compilation unit you are missing has nothing to do with files you #include (which are only relevant for compilation, not linkage)
7,367,957
7,368,019
Double in object method not accepting fractional values?
I am having trouble with a C++ object-orientated script. When I create an object, I wish to calculate an AttributeQ based on its attributes MyAValue, MyBValue, and MyCValue. While using the Visual 2010 debugger, I noticed that TempAttribueQ seems to always be 0 (except before it is initialized of course). Assuming Del...
When you divide one integer by another, you get an integer result. Change either or both the constants to non-integer to fix it - C++ rules will result in the other being converted to floating point before the division takes place. All of the following will work: 1.0 / 3.0 1 / 3.0 1.0 / 3 An integer will get converte...
7,368,200
7,368,208
Bit shifting number gives wrong output `std::cout`
unsigned int command = 4; cout << command; command = (command << 1); cout << command; command = (command << 1); cout << command; Output: 4 8 10 Why is is the output of the last line 10, and not 16?
There's probably a cout << hex somewhere before this code runs. Either that or you accidentally set cout to format numbers in hexadecimal. If you add: command = (command<<1); cout << command; It should print out 20 in hex mode.
7,368,330
7,368,424
Static members and the default constructor C++
I came across a statement in my book that said: You don't have to initialize a static member when you declare it; C++ will invoke the default constructor if you don't. This really has me confused as to what it means. Are they talking about object members only? If so, at what point would it call the default constructo...
Let's break it down. Suppose there's some class Foo; somewhere. Now we make this a static member of our class, class Star { static Foo z; // ... }; Now in essence that declares a global object Foo Star::z -- so how does this get instantiated? The standard tells you: it gets default-constructed. But remember that y...
7,368,651
7,380,593
How do you find what GroupPolicy objects are attached to a container/domain/site?
I've got a problem where I need to interleave settings made on the host/user/containers/domain/site with the group policy settings attached to the containers/domain/site. We can walk the ad tree for the host and the user and have those settings. We have our group policy list & objects and those settings. I'm just havin...
You need to look at the gpLink attribute of each site, domain, and OU. You can also look at gpOptions for a handful of related flags. The gpLink attribute will have the DNs of each GPO applied to that object as well as whether or not the link is enabled or not.
7,368,947
7,368,964
Question about using a switch statement
First, I realize that from a performance perspective, the design of this switch statement is slow because cout is being called several times in certain cases. That aside, is this style of writing a switch statement not good coding practice. In other words, would it be better to handle each case individually and break o...
Switch statements aren't slow, they're usually optimised to jump-tables by the compiler. And if you're sure that switch statement works as expected, it's fine and is a pretty cool way of doing it. That said, you'd have the same number of cases if you handled each one individually. If that's all you're doing, I'd probab...
7,369,005
7,370,030
Add a QLineEdit to a qtoolbar in qtcreator (designer)
I have trouble with adding controls as a QLineEdit to a QToolbar from the IDE itself not by adding code (I can't do any GUI coding without a WYSIWYG editor) I'd also like help with overlapping controls on it. Another last question is how can I get a link from QWebview by hovering it (more like when web browsers show yo...
There are some things you can't do with the Designer, and adding a QLineEdit or other widgets to a QToolBar is one of them, but you can do it easily with code: ui.toolBar->addWidget(yourLineEdit); // or you can place it after an existing action: ui.toolBar->insertWidget(ui.anActionInYouToolBar, youLineEdit); QWebPage...
7,369,283
7,369,306
An alternative to a static variable in a member function
I have been relying on the misconception that static variables defined in member functions were limited to the specific class instance. To illustrate my misconception: #include <iostream> #include <string> struct Simple { template<typename T> T & Test(const T & Value) { static T Storage = Value; ...
If I understand your confusion, the alternative is member variables... template<typename T> struct Simple { T storage; T & Test(const T & Value) { storage = Value; return Storage; } };
7,369,314
7,370,311
GCC, Clang, and IBM disagree on how to perform template-parameter-dependent name lookup. Which one is right?
Consider this example I found on IBM's website: #include <iostream> using namespace std; void f(double) { cout << "Function f(double)" << endl; } template<class T> void g(T a) { f(123); h(a); } void f(int) { cout << "Function f(int)" << endl; } void h(double) { cout << "Function h(double)" << endl; } void i() {...
They are all correct. No really, read on... template<class T> void g(T a) { f(123); h(a); } Here, f is a non-dependent name but h is a dependent name according to 14.6.2/1. f is looked up Non-dependent names used in a template definition are found using the usual name lookup and bound at the point they are use...
7,369,344
7,369,771
How to (un)escape strings in C/C++?
Given a counted string (either an array of characters, or a wrapper like std::string), is there a "proper" way to escape and/or unescape it in C or C++, such that "special" characters (like the null character) become C-style-escaped and "normal" characters stay the way they are? Or do I have to do it by hand?
This is a function to process a single character: /* ** Does not generate hex character constants. ** Always generates triple-digit octal constants. ** Always generates escapes in preference to octal. ** Escape question mark to ensure no trigraphs are generated by repetitive use. ** Handling of 0x80..0xFF is locale-dep...
7,369,412
7,369,463
Iterating over `hash_multimap` by key and then by value
I need to execute some code on all the values of a key, and I need to repeated that action for every key. I look for something like: for(auto key_iterator = hash_multimap.begin_keys(); key_iterator != hash_multimap.end_keys(); key_iterator++) { auto key = key_iterator->key; // set up state for(auto valu...
You can use lower bound and upper bound to achieve this. For example try - auto value_iterator = hash->begin(); while( value_iterator != hash->end() ){ { auto lIter = hash->lower_bound( value_iterator->first ); auto uIter = hash->upper_bound( value_iterator->first ); while( lIter != uIter ){ ...
7,369,654
7,370,402
Finding point of rotation in the sorted array
I am trying to locate the point of rotation in a sorted array through a modified binary search. Consider this array int values[9]={7, 8, 9, 1, 2, 3, 4, 5, 6}; The point of rotation here is at index = 3 i.e at 9. I wrote this function for the above operation. void FindRotationPoint(int values[], int numvalues) { in...
This works: void FindRotationPoint(int values[], int numvalues) { int first =0; int last = numvalues-1; int middle=0; bool moreTosearch= (first<=last); while(first<last) { middle = (first+last)/2; if(values[first]>=values[middle]) //Keep looking right if the middle value in array...
7,369,663
7,375,759
LibCurl - Release Static Lib linking problems
I have been at this for some time now. I hope someone can tell me what I am doing wrong. These are the steps I have taken so far: -Downloaded the latest version of cURL (7.21.7). -Opened the solution in Visual Studio 2010 using the vc6curl.dsw and converted the projects to VS2010. -Set the libcurl project configuration...
The best way to build CURL for windows is to use NMake with provided Makefiles. You can Modify Makefile in root folder of CURL to set VC version you use and then run nmake vc-all (or choose any other VC target suitable for you). Check "Win32" section of ./docs/INSTALL file. Use Makefile.vc from ./winbuild folder. Che...
7,369,679
7,369,694
Unable to dynamically load a library in Lua with package.loadlib
I'm trying to create a library that I can load into Lua with require or package.loadlib, but I have so far been unsuccessful. The library itself is in C++, but as far as I can tell I've taken the step necessary to properly export the function to load the library. In a nutshell, this is the relevant section of my C/C++ ...
In the Lua manual, it says, "libname must be the complete file name of the C library, including if necessary a path and extension." Is your .so file in that directory, with that name?
7,369,684
7,369,706
How to get two integers separated by space in a char[]?
I will be getting a string of numbers that looks like this. 12 45 Two integers separated with space. The output will be 57. I have tried using, string numbersstream; cin >> numbersstream; istringstram twonumbers (numbersstream); twonumbers >> a >> b; But each time I run it, only a is correct, b isn't. What other func...
The problem is with your input from cin. Using operator>> is whitespace delimited. So if the user types "12 45", only the 12 will be extracted. You could use getline instead: getline(cin,numbersstream);
7,369,803
7,369,815
Unexpected Output when adding two float numbers
I wrote the following C++ code: float a, b; int c; a = 8.6; b = 1.4; c = a + b; printf("%d\n", c); The output is 10. But when I run the following code: float a, b; int c; a = 8.7; b = 1.3; c = a + b; printf("%d\n", c); The output is 9. What is the difference between the two, as they are giving different outputs?
There is no such number as 8.7 or 1.3 in floating point. There is a number 10, and a number -6.5, and a number 0.96044921875... but no 8.7 or 1.3. At best, your computer can round 8.7 to the nearest floating point number, and round 1.3 to the nearest floating point number as well. The computer adds these rounded numb...
7,369,818
7,369,837
Return array from function C++
I'm new to C++, I have experience with C#, Objective-C and JavaScript. At the moment I'm trying to write a function that takes a path and returns a directory listing (all files and folders at that path). I'm doing this on Ubuntu. Here's my code so far, to be honest I'm struggling to understand the double pointer syntax...
*directoryEntries = new dirent[MAX_FILES]; What if the number of directories is greater than MAX_FILES? How do you know that it cannot be greater than MAX_FILES? I think you should use std::vector<dirent> instead of dirent*. Many of the problems will be solved. I would implement the function as: std::vector<dirent> F...
7,369,833
7,369,879
Is there any way to add a source file through a pragma?
Is there any way, via a pragma directive, to add a source file to the list of files to be compiled in Visual Studio 10? That way header files could bring their implementation files along with them whenever they are included.
As far as I know there is no such thing. It would make it awfully complicated to keep track of project dependencies if something like that was supported. But there is something like that for libraries. Say you have a library called library.lib and a header file that declares the symbols for this library called library....
7,370,063
7,370,118
Using VS2010 as an IDE and using MSVC 2005 as a compiler
I wanted to use VS2010 and an IDE and using MSVC 2005 as a compiler, how can I do that?
Visual Studio 2010 includes the capability of multi-targeting C++ projects (native or managed) using the Platform Toolset option. The built-in support is for v100 (VS2010) and v90 (VS2008). See: C++ Native Multi-Targeting which shows how to extend the feature to support v80 (VS2005). See these special MSDN instruction...
7,370,109
7,370,156
Why don't rvalues have an address?
Why don't rvalues have a memory address? Are they not loaded into the RAM when the program executes or does it refer to the values stored in processor registers?
Your question ("Why don't rvalues have a memory address?") is a bit confused. An rvalue is a kind of expression. Expressions don't have addresses: objects have addresses. It would be more correct to ask "why can one not apply the address-of operator to an rvalue expression?" The answer to that is rather simple: yo...
7,370,235
7,370,341
How to create solid extrusion of bitmap with OpenGL?
I have a bitmap image (RGB, no alpha), like the image below (letter 'R'): Which is the best way, with OpenGL & VC++, to create the extrusion of the bitmap? Parameter is a 3f vector. Either solid extrusion or surface only extrusion is ok. Any idea?
Like said so often: OpenGL is "merely" a drawing API, rasterizing triangles to the screen. It doesn't deal with scenes. It doesn't deal with geometry. Extrusion of a bitmap requires two specific tasks, neither of which OpenGL can do for you: Vectorizing the outline. Extruding the outline. The hard part is vectorizing, ...
7,370,396
7,370,460
Templates terminology
template <typename T> void quark(T&& t) { } Previous code has that explanation: When we call quark(up), template argument deduction is performed. quark() is a function template with a template parameter T, but we haven't provided an explicit template argument (which would look like quark<X>(up)). Instead, a templat...
Template parameter is T. Template argument is the actual type, the value of T. Consider this, template<typename T, typename U> void f(T a, U b); f<int,char>(10, 'A`); Here T and U are template parameters, and int and char are template arguments. Since it's a function template, you can also say function template para...
7,370,535
7,370,550
Priority of #define vs. const declaration
can a #define "overwrite" a const variable or vice versa? Or will it lead to a compiler error? //ONE #define FOO 23 const int FOO = 42; //TWO const int FOO = 42; #define FOO 23 What value will FOO have in both cases, 42 or 23?
First one will give compilation error. Macros are visible from the point of their definition. That is, first one is equivalent to: //ONE #define FOO 23 const int 23= 42; //which would cause compilation error And second one is this: //TWO const int FOO = 42; #define FOO 23 //if you use FOO AFTER this line, it will be r...
7,370,577
7,370,608
How can I ensure a read-only transaction in SqLite?
I have public interface which allows people to interact with the database by typing in sql commands. However, I do not want them to change the database in any way (and if possible, not access certain tables). As I understand though, SQLite has no concept of users, so how do I accomplish this?
Copy the "master" database file first and open that :-) No, really, this is a serious suggestion. Otherwise, depending on how SQLite is accessed, the SQLITE_OPEN_READONLY flag that can be passed to sqlite3_open_v2. This applies to the entire connection -- and all transactions on that connection. Another option is to li...
7,370,674
7,370,720
Program with phreads works for some time and then stops
I am struggling with a program that uses pthreads. Here is a simplified version of the code I have difficulties with: #include <cstdlib> #include <iostream> #include <pthread.h> pthread_t* thread_handles; pthread_mutex_t mutex; pthread_cond_t cond_var = PTHREAD_COND_INITIALIZER; int thread_count; const int some_count...
From this: The pthread_cond_wait() and pthread_cond_timedwait() functions are used to block on a condition variable. They are called with mutex locked by the calling thread or undefined behaviour will result. I understand the mutex should be locked when this function is being called, from your code I can see that...
7,370,810
7,370,816
What does the m in mVariableName mean?
I've seen several occurrences in tutorials where i variables with an "m" in front of the actual name. At first I thought it meant "my" but after really keeping a lookout for these "m"'s I'm no longer sure what it means. Does anyone know where this convention comes from?
It's commonly used to mean that variable is a member of class. For example it's useful in situations like this: someclass::somefunc() { ... . . m_myvar = 1; lvar = 2; . . . } You can tell at a glance that m_myvar is a member of someclass but lvar is not.
7,370,887
7,370,903
Convert an ASCII string to long long
I've got some lines of information from a data-file in C++. One information is a 12 character long number. How can I convert this from string to long long (I think long long is most suitable for this) without data loss?
In C++, there is no long long data type. It's available in C99. However, you can use int64_t. Include <stdint.h>. Use boost::lexical_cast to convert string into int64_t. Or you can write a convert function yourself as: int64_t convert(const std::string &s) { if(s.size() == 0 ) std::runtime_error error("inval...
7,371,031
7,371,463
How should I do depth independent blending?
I'm working on an OpenGL 3 renderer for a GUI toolkit called Gwen. I nearly have everything working, but I'm having some issues getting everything to blend correctly. I've sorted the triangles by which texture they use and packed them into a VBO, so with the Unit Test, it basically boils down into 3 layers: Filled Re...
You're drawing a GUI; batching shouldn't be your first priority for the simple fact that a GUI just doesn't do much. A GUI will almost never be your performance bottleneck. This smells of premature optimization; first, get it to work. Then, if it's too slow, make it work faster. There is no simple mechanism for order-i...
7,371,087
7,371,096
C++ friend inheritance?
Does a subclass inherit, the main class' friend associations (both the main class' own and other classes friended with the main class)? Or to put it differently, how does inheritance apply to the friend keyword? To expand: And if not, is there any way to inherit friendship? I have followed Jon's suggestion to post up t...
Friendship is not inherited in C++. The standard says (ISO/IEC 14882:2003, section 11.4.8): Friendship is neither inherited nor transitive.
7,371,220
7,372,639
Edit controls won't get focus! win32 c++
Edit Control's in my Win32 App just refuse to take focus!. As a result, I cannot enter text in them. The controls worked fine before, and now just refuse to work! Here's a link to the code: http://dl.dropbox.com/u/35856163/src.zip
Next time post code right here, and at least try to compile it! I get 18 errors just trying to compile your file. Your code is also very hard to read, so I can't really say what happens where. You are mixing chars with wchars_t thus you can have memory corruption. char Buffer[Length() + 1]; shouldn't even compile! What...
7,371,255
7,371,327
Linking against Boost.MPI and Boost.Serilaization in Ubuntu
I have ubuntu with boost, boost.MPI installed. I don't know how can I link against Boost_MPI and Boost_Serialization though. For commands like this, mpic++ -I/path/to/boost/mpi my_application.cpp -lboost_mpi-gcc-mt-1_35 -lboost_serialization-gcc-d-1_35.a how can I know the appropriate names of the libraries ? Tarek
I would suggest the following steps: Use synaptic package manager and make sure that libboost-serialization-dev and libboost-mpi-dev are installed. Try lib names without version number. mpic++ my_application.cpp -lboost_mpi -lboost_serialization If it doesn't work go back to the package manager, select the library an...
7,371,467
7,371,513
Multiple condition clause in C/ C++
My aim is to get two numbers and perform an corresponding to the values they hold: For ex.. Let the vars be x and y. I need to compute the value of another var z, as follows: z = x + y // if x = y = 1 z = x - y // if x = 0 and y = 1 Since i need to use it several times, it would not be efficient to use if else within a...
If the vars are integers/any other primitive type you can't improve the performance, since the compile will usually translate it one assembly code line. such as sub eax, ebx Anyhow, as mentioned before, you can't do it on compile time since x,y values are not known at compile time. you can hint the compiler to save x a...
7,371,470
7,371,495
C++ class design questions
I have a class Node. This class can add or remove other nodes relative to itself. Node is used by a List class. To prevent the nodes being modified directly (externally, IE not by the appropriate classes) during usage and causing problems with the List class, the nodes add/remove functions are either protected or priva...
I would make Node a protected nested class of List: class List { ... protected: class Node { ... }; }; This way, only List and its subclasses can access it. Since it is nested within List, list may access its private/protected members and functions. It also helps to highligh...
7,371,661
7,371,677
C++ inheritance questions
When would you use: A private constructor/destructor? A protected constructor/destructor? A protected inherited main class? class Name : Protected Main A private inherited main class? class Name : Private Main If it's too broad, can a single short example for each question of one instance of where you might use it, a...
A private constructor/destructor See here for private destructors, but a private constructor when you don't want anyone constructing instance of your class. A protected constructor/destructor I don't know about a protected destructor, but a protected constructor when this is an inner class and you only want the ...
7,371,847
7,372,874
How to keep private keys in secured memory
I have a private key that I decrypt using a password from the user, but I need to use this private key quite often, and I don't want to keep it decrypted in the memory. One option I thought of is encrypting the private key with a randomly generated one time password, and every time I use it, to replace the password, bu...
By definition you are looking for means of Security though obscurity. In this case the user has more control over the device than you do. The secret must exist in plain text at some point, and the attacker (the user), can attach a debugger and view this value. There will never be a solution to this problem, it i...
7,371,861
12,620,678
How to write Main-Loop for a server?
I have a simple fcgi server written in c++ - for now it's single threaded. I saw the main loop for example like accept_connections(); handle_data();` handle_connections(); but what if I want to respond to each client simultaneously? Because if I understand this, server first accepts new connections and iterate over th...
I solved it earlier but i want to answer my question. Solution I made: 1 acceptor thread - (accept() for new incoming connections in blocking behavior) and assigning connections to network threads with load balancing N network threads where N = (1 thread per 1000 clients) with nonblocking behavior: initialize while s...
7,371,928
7,372,091
c++ pow(2,1000) is normaly to big for double, but it's working. why?
the code: #iclude <math.h> int main(){ double somenumber = pow(2, 1000); printf("%lf\n", somenumber); return 0; } i get this huge number: 107150860718626732094842504906000181056140481170553360744375038837035105112493612249319837881569585812759467291755314682518714528569231404359845775746985748039345677748242309854210...
This is obviously to big for double. How it's working? 21000 is within the range of numbers that can be represented by a double. So this number obviously is not too big for a double. I suspect that what you mean by "too big" is that the number of digits printed is much greater than the 16 or so digits that can be sto...
7,372,012
7,372,068
Line Feed and Carriage Return
Recently I was working with some strings, text input, things like that and I realized I got little confused about 2 characters - LF(10) and CR(13). Every time I needed to start new line I used std::endl for c++ string and \n which is LF for c-strings. However I'm now using one library which on return key press sends me...
Inside your C and C++ programs all you need (at least, when dealing just with the standard library) is \n, which, when sent to any C/C++ stream opened in text mode (i.e. when you don't specify b into the fopen and ios::bin for C++ streams), is automatically translated to the line terminator of the current platform. Tha...
7,372,024
7,372,043
Allocation of memory ( C++ ) Compile-time/Run-time?
I am not sure how appropriate is this question, but - I am curious about how the compiler sets memory aside for an object (allocation of memory) even before it is constructed (before even the constructor is called!). How does it happen for primitive datatypes? This sounds a bit naive, but what exactly is it ? Is it ent...
Memory allocation always happens at run time. Memory reservation, for objects that reside on the stack, or for static variables, happens at compile time (or at run time for C99 VLAs). Memory for an object's members is always in place before the constructor runs. It is the job of the compiler and its runtime support to...
7,372,085
7,372,176
c++ IPC through streambuf on Windows
I have a message object serialized as binary data stream (it can be any std::streambuf), and i want to transfer it to another process. The key is, server application must handle many clients, connection have to be asynchronous (because of multiple clients), and bidirectional (under the hood it may be implemented by two...
You can use named pipes in windows. See MSDN ref: http://msdn.microsoft.com/en-us/library/aa365150%28v=vs.85%29.aspx You can also set it to be full duplex (bi-directional) and asynchronous. If you are familiar with File I/O APIs on windows then it should be straightforward to use.
7,372,132
7,372,163
C++ STL sort() function, binary predicate
I have a piece of code that confuses me: sort(data, data+count, greater<int>() ); it is a sort function in the C standard library. I am having trouble figuring out the meaning of the third argument. I have read that it is called a binary predicate. What does that mean and how can I make my own such predicate?
The third argument is called a predicate. You can think of a predicate as a function that takes a number of arguments and returns true or false. So for example, here is a predicate that tells you whether an integer is odd: bool isOdd(int n) { return n & 1; } The function above takes one argument, so you could call...
7,372,328
7,372,386
ICU C++ Converting Encodings
As I understand it, different locales have different encodings. With ICU I'd like to convert from a UnicodeString to the current locale's encoding, and back. Specifically I'm using Boost's Filesystem library, which in turn uses either Windows' UTF-16, or Linux's UTF-8 encodings. Is there a way to reliably do this using...
You can use ICU, but you may find iconv() sufficient, which is a lot simpler to set up and operate (and it's part of Posix, and easily available for Windows). With either library, you have to convert your unicode string to a wide string. In iconv() that target is called WCHAR_T. Once you have a wide char, you can use i...
7,372,439
7,372,467
Operator overloading and pointers to objects, c++
I've build a class representing a matrix and I override all the arithmetic operators. Here's an example of overloading the unary minus RegMatrix.h: const RegMatrix operator - (); RegMatrix.cpp const RegMatrix RegMatrix::operator - () { RegMatrix newMatrix(*this); newMatrix *= -1; return newMatrix; } Now, ...
The type of a is RegMatrix *, not RegMatrix; if you want to apply operators on the object to which a points you have to dereference a (*a), apply the operator to it (-(*a)) and, if you want a separate instance of it on the heap, create a new copy of it on the heap with new and the copy constructor: RegMatrix* a = new R...
7,372,448
7,372,506
C++ Macro to conditionally compile code?
I want to compile code conditionally based on a macro. Basically I have a macro that looks like (Simplified from the real version): #if DEBUG #define START_BLOCK( x ) if(DebugVar(#x) \ { char debugBuf[8192]; #define END_BLOCK( ) printf("%s\n", debugBuf); } #else #define START_BLOCK( x ) (void)0; ...
So you want conditional blocks with their own scope? Here's a quite readable solution that relies on the compiler to optimize it away: #define DEBUG 1 if (DEBUG) { // ... } And here is one that is preprocessor-only: #define DEBUG 1 #ifdef DEBUG #define IFDEBUG(x) {x} #else #define IFDEBUG(x) #endif IFDE...
7,372,528
7,377,337
Technique for factoring find like methods?
I am looking for a technique to factor find like methods. The problem is the following. I need a find method on a container that does not need to modify the container contents to do the search. However there should be a const and a non-const version of it since, it could lead to the modification of the container in the...
There might not be very good solutions. Both const overloads and iterator/const_iterator are rather clumsy tools to work with. In the first case, it might be better to let the const version do the work and the non-const version do the casting. That way the compiler would be able to check if your algorithm indeed doesn'...
7,372,552
7,372,614
Why doesn't c++ recognize a string when trying to convert it into another type?
I have a fairly simple class that looks like this: class Person { public: Person(string name): _name(name) {}; void greet(const Person& person) const { cout << "Hello, " << person._name << "!" << endl; }; private: string _name; }; Note that the greet method takes...
maher is a const char[6], and sam is a const char[4], and both decay to const char * implicitly, but none of them is actually a std::string. In function calls, the C++ standard allows an implicit conversion to be performed if there's a non-explicit constructor of the target type that accepts the type of the actual valu...
7,372,590
7,372,661
Callback requires const function, how to pass instance member of object
I am using WebKitGTK+ in a larger GTKmm/C++ application. I am using JavaScriptCore to interact with the WebKitWebFrame and JSContext within. I am stuck now as I need to interact with a GTK GUI component when a javascript function is called. To this end I found the JSObjectMakeFunctionWithCallback function. JSStringRe...
The callback is required to be a pointer to a free function, so no amount of magic can get you to pass a member function directly. One common solution is to make an intermediate global free function that holds the object instance: JSValueRef ClickCallback(...) { Foo & obj = getInstance(); // implement this somehow ...
7,372,683
7,384,287
GmfBridge doesn't connect sink filter with source filter
I am trying to use GmfBridge library to dynamically change source filters from cam to file and vice versa. All functions return S_OK (well, almost all - pMediaControlOutput->Run() returns S_FALSE actually, but in msdn said that this can be ok too), so I've assumed that all is ok but data isn't transfered to the other s...
It's really ridiculous but about a few minutes ago after a day of searching we have found the answer. All deal was about really huge hole in GmfBridge. I was giving wrong interfaces here (there are graphs instead of bridge's sink and source filters) 'coz function needed pointers to IUnknown: hr = bridge->BridgeGraphs( ...
7,372,918
7,372,938
What's the Use of '\r' escape sequence?
I have C code like this: #include<stdio.h> int main() { printf("Hey this is my first hello world \r"); return 0; } I have used the \r escape sequence as an experiment. When I run the code I get the output as: o world Why is that, and what is the use of \r exactly? If I run the same code in an online compiler...
\r is a carriage return character; it tells your terminal emulator to move the cursor at the start of the line. The cursor is the position where the next characters will be rendered. So, printing a \r allows to override the current line of the terminal emulator. Tom Zych figured why the output of your program is o worl...
7,373,200
7,373,438
Chopping of digits (after the dot) in C++
i need to "chop off" a 'double' so that he'll have 3 digits after the dot (not rounding, just cut everything else off). Here is my code: double multiply_by = (pow(10.0, _digits_percision)); _number = (_number * multiply_by); _number = (int) _number; _number = (_number / multiply_by); When i'm inputing 1.001, my output...
Your computer is using a base 2 floating point representation. When you input 1.007, the computer converts this to the closest possible representation. It cannot represent 1.007 exactly. The representation is instead something like 1.0069999999999999. Multiply by 1000 and you get 1006.9999999999999. Converting to an in...
7,373,205
7,373,228
Returning double with precision
Say I have a method returning a double, but I want to determine the precision after the dot of the value to be returned. I don't know the value of the double varaible. Example: double i = 3.365737; return i; I want the return value to be with precision of 3 number after the dot Meaning: the return value is 3.365. Anot...
What you want is truncation of decimal digits after a certain digit. You can easily do that with the floor function from <math.h> (or std::floor from <cmath> if you're using C++): double TruncateNumber(double In, unsigned int Digits) { double f=pow(10, Digits); return ((int)(In*f))/f; } Still, I think that in ...
7,373,264
7,373,336
how to deal with deallocation of copied pointers
I'm trying to build a struct with a constructor and destructor in C++ (is that a bad thing to do? Should I use a class instead?), because I would hate to write unnecessary 10 lines of delete struct.member every time the members should be deallocated The members of the struct are mostly pointers to other types. However...
All of those pointer data members are pointers to COM types that are reference counted. Release does not necessarily destroy the pointed-to object. It decrements the reference count and only destroys the object if there are no more references to it. Rather than using raw pointers and calling AddRef and Release yourse...
7,373,480
7,373,489
Why can I assign/compare int and char in C
I have the code like this : #include <stdio.h> main() { int c; c = getchar(); while (c != EOF) { putchar(c); c = getchar(); } } The C documentation says that the getchar() returns the int value. And in the above program we have assigned c type as an int. And most importantly EOF is a integer constant defined in the ...
No. It simply means that the returned value which is an int, implicitly converts into char type. That is all. The compiler may generate warning messages for such conversion, as sizeof(int) is greater than sizeof(char). For example, if you compile your code with -Wconversion option with GCC, it gives these warning mess...
7,373,649
7,373,723
what are good mesh animation techniques?
I want to create a 2D game with monsters build as a custom vertex mesh and a texture map. I want to use this mesh to provide smooth vector animations. I'm using opengl es 2.0. For now the best idea i have is to write a simple editor, where i can create a mesh and make key-frame based animation by changing position of e...
You said this is a 2D game, so I'm going to assume your characters are flat polygons on to which you apply a texture map. Please add more detail to your question if this is not the case. As far as the C++ part I think the same principles used for 3D blend shape animation can be applied to this case. For each character ...
7,373,671
7,373,733
c++ weird struct and bitset error
I have this inside my private class declarations #include "stdafx.h" using namespace std; template <typename Key, typename T> class A{ //.... private: static const unsigned int HSIZE = 32; struct Bucket { Key key; T value; bitset<HSIZE> jumpMap; ...
Have you included the bitset header? I think you have missed it?
7,373,770
7,373,939
printing negative value in C++ base 8 or 16
How is C++ supposed to print negative values in base 8 or 16? I know I can try what my current compiler/library does (it prints the bit pattern, without a minus in front) but I want to know what is should do, preferrably with a reference.
From §22.2.2.2.2 (yes, really) of n1905, using ios_base::hex is equivalent to the stdio format specifier %x or %X. From §7.21.6.1 of n1570, the %x specifier interprets its argument as an unsigned integer. (Yes, I realize that those are wacky choices for standards documents. I'm sure you can find the text in your favor...
7,373,852
7,373,873
interpret unsigned as signed
I'm working on an embedded platform (ARM) and have to be careful when dealing with bit patterns. Let's pretend this line is beyond my influence: uint8_t foo = 0xCE; // 0b11001110 Interpreted as unsigned this would be 206. But actually it's signed, thus resembling -50. How can I continue using this value as si...
The following works fine for me, as it should though as the comments say, this is implementation-defined: int x = (signed char)(foo); In C++, you can also say: int x = static_cast<signed char>(foo); Note that promotion always tries to preserve the value before reinterpreting bit patterns. Thus you first have to cast ...
7,373,928
7,373,944
Generic: Version number bit shift routine
I would like the best routine the community can devise which will provide a version number string using only 32 bits. The version number will contain three parts: major, minor, and build number. Bonus karma points for answers that include Java source. Update 1 Ok, so to clear up some confusion the major and minor fiel...
Java: class Version { public char major; public char minor; public short build; // And the rest of your class definition ... } Edit: So you want to do it with a bit shifts and store it in a 32-bit integer (even though using a class or struct would still use the same amount of storage space)? An examp...