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,835,940
5,836,168
Can I call an Objective-C class from a C++ program?
I have an open source C++ project. My aim is now to extend this project with additional code. This code is Objective-C code (because I don't know C++). I have already found a way to call an Objective-C function from a C++ class (Calling Objective-C method from C++ method?) But, when I try to compile my C++ code with XC...
Xcode freezing is definitly a bug, it should compile or give an error. Try switching to another compiler in your project settings. As long as the c++ code is compiled in objective-c++ mode it should work. AFAIK it will only compile in objective-c++ mode if the file extension is .mm or if you explicitly tell the compil...
5,836,142
5,836,802
Mock Device connecting through USB
I have a device and the drivers for this device. What I would like to do is build an application that mocks a USB device to communicate with a third party application. More specifically, I am attempting to build an application that can mock a USB device that mimics a Microsoft Zune. I want to make it so my applicatio...
Are you able to replace the DLLs used by the zune client software with your own DLLs? In that case, you could wrap the original DLLs with your DLLs and intercept the operations. Update: To find out the signatures of the functions in the DLL, take a look at the Dependency Walker tool, which will list the exported func...
5,836,171
5,836,188
Can't delete dynamically allocated multidimensional array
I can't delete the dynamically generated arrays. There is how I create them: template <typename T> T **AllocateDynamic2DArray(int nRows, int nCols){ T **dynamicArray; dynamicArray = new T*[nRows]; for( int i = 0 ; i < nRows ; i++ ){ dynamicArray[i] = new T[nCols]; for ( int j=0; j<nCo...
Try this: for (int qq=0; qq < KrylovDim + 1; qq++) { delete [] h[qq]; } delete [] h; So basically you are doing the reverse of the allocation process for( int i = 0 ; i < nRows ; i++ ){ dynamicArray[i] = new T[nCols]; // Instead of allocating now delete !
5,836,178
5,836,452
why unordered associative containers do not use allocator_traits<T> in C++0x
Why don't C++0x unordered associative containers use allocator_traits to define their member types pointer and const_pointer? For example, sequential and ordered associative containers use the following definition: typedef typename allocator_traits<Allocator>::pointer pointer; typedef typename allocator_traits<Allocato...
I don't think you're missing anything. Here's your chance to participate in the standards process. Please submit an issue. The directions on how to do so are here: http://lwg.github.com/issues/lwg-active.html#submit_issue I scanned, but did not find an existing issue on this subject.
5,836,324
5,836,532
How to cheaply assign C-style array to std::vector?
Currently I do the following: // float *c_array = new float[1024]; void Foo::foo(float *c_array, size_t c_array_size) { //std::vector<float> cpp_array; cpp_array.assign(c_array, c_array + c_array_size); delete [] c_array; } How can I optimize this assigning? I would like not to perform elementwise copy but jus...
The current std::vector doesn't provide any capability or interface to take ownership of previously allocated storage. Presumably it would be too easy to pass a stack address in by accident, allowing more problems than it solved. If you want to avoid copying into a vector, you'll either need to use vectors through your...
5,836,425
5,836,502
c++ two dimensional array question
I would like to create something like a pointer to a 2 dimensional array of pointers (with the width and the height of x). Will this code do what I expect? (Create array elements, writing out some information about them, then release all the allocated memory.) int main(int argc, char** argv) { int x = 3; Node *...
I recommend that you use vector< vector<Node> >, boost::multi_array, or you can roll-up your own dynamic 2D array class (it's not that hard) that is a wrapper around a flat 1D std::vector. All of the above solutions will store your Node objects in the heap, and will take care of cleaning up memory. Here's an example of...
5,836,463
5,852,921
Xcode will not start from the Applications folder
I am currently on a Mac, and I tried copying the Xcode icon to the applications folder and now Xcode doesn't work. I get the following error when trying to open Xcode: Xcode cannot be opened because of a problem. Check with the developer to make sure Xcode works with this version of Mac OSX.... I tried dragging back X...
I dragged Xcode from the folder that it wasn't supposed to be in to Developer -> Applications, which is the folder it should be in and it worked
5,836,542
5,836,568
Value not assigned to handle when build using Release Configuration in VS2010
I use VS2010 and I have encountered following problem: HWND handle = NULL; handle = pPlatform->getWindowHandle(); When I debug this code in debug configuration a correct value is assigned to "handle", but when I debug this in release build "handle" stays NULL. getWindowHandle() is just a simple accessor: HWND Platfor...
The Release build includes optimizations, and sometimes the debugger might see the wrong value for variables that get optimized. It makes Release builds harder to debug, but that's exactly why they're not called Debug builds. :) In short, if you just have to debug a release build but your debugger is playing tricks on ...
5,836,611
5,841,778
glGenBuffers returning non-unique names
I thought that this was impossible but I'm seeing it with my software. I have built a wrapper object to manage my buffer objects (I am working with shared contexts so I can't use VAOs), and the VBO side of things was working fine until I starting testing it with IBOs (glDrawElements(), I'm using a pure OpenGL 3+ envir...
Thanks to Ilian Dinev over at the OpenGL.org forums for pointing out this stupid error. I created my Buffer object on the stack and conveniently had it's destructor call glDeleteBuffers(). Fantastic bit of design.
5,836,948
5,838,527
Boost.Extension - simple inheritance sample - why we see no animals on linux?
So I try to port some Boost.Extension samples for linux. The sample is described here. Here is my code port (classes with animals, animal prototype, main app, general all port idea is described here, and some current linux progress here (some samples really work as needed!)). When I compile this sample under linux it ...
I debugged things on linux, good news: You are running into bullet no. 3 from Jeremy Pack's post: RTTI does not always function as expected across DLL boundaries. Check out the type_info classes to see how I deal with that. I have a tiny workaround patch (below) to boost/extension/impl/typeinfo.hpp (but you need to t...
5,837,070
5,837,197
Release build not working when run without debugging in VS2010
I encountered following problem: I write program in c++ using VS2010. Debug build works properly when run with/without debugging in VS. When I launch built executable directly it also works. Release build works when run with debugging in VS and alsp when I launch build executable directly. Unfortunately, program does n...
It seems most likely you have some sort of memory error/corruption that just happens to work ok in the debugger. You can try using couts to isolate how far/where it dies, or try a tool like Purify (or valgrind for free if you can port to Linux).
5,837,106
5,837,159
CXXFLAGS modification of Qt pro file?
Possible Duplicate: Configuring the GCC compiler switches in Qt, QtCreator, and QMake I would like to use -O1 instead of -O2 in my makefile (CFLAGS and CXXFLAGS) for my Linux build. My understanding of how these makefiles are generated based on the .pro file is somewhat lacking. This is because the version of Qt com...
You were very close. What you want is: QMAKE_CXXFLAGS += -O1 If you would like to apply flags to just the release build, then you can use this: QMAKE_CXXFLAGS_RELEASE += -O1 You also probably want to change your condition to be a little more flexible. In summary, something like this: *-g++* { QMAKE_CXXFLAGS += -O1 ...
5,837,419
5,837,470
Specific things with type cast operator
#include <iostream> using namespace std; struct A { A(int a):a(a){} int a; }; struct B { operator A() { return 10; } }; int main() { B b; cout << ((A)b).a << endl; return 0; } This code compiles and prints 10 in visual studio. But in wikipedia next to cast operator I found th...
operator A() is a user-defined conversion operator. It's job is to return an A by-value when you cast a B to an A. Your operator A() function is returning a literal integer value, 10. But operator A needs to return an A, so A's convert constructor is called with the value 10. This results in a temporary A being cons...
5,837,445
5,837,474
Vector and assignment operator
I need to do a deep copy of a vector to a vector. Ex - vector<char> a; // add some things vector<char> b; a = b; I know that I can always say a(b) but the problem is I must reassign more than once and to a global variable, so I'm pretty sure I can't use the copy constructor once it's already created. Is the assignme...
Yes, the assignment operator is overloaded for std::vector and you can safely use a = b;
5,837,621
5,837,649
Why Visual Studio in C++ is not as intelligent as it's in C#?
I'm wokring on a homework in C++ in Visual Studio 2010, I've found that Visual Studio is not as wonderful as it is in C#. No intellisense , No code formating and stupid load of error messages which they might be gone togother if one error has been fixed. Why that?
Microsoft has not been putting much effort into its C++ tools since .NET appeared. In a lot of ways, the current IDE is worse than Visual C++ 6. Here is the Visual C++ team's blog entry about recent C++-related work and why there is no Intellisense for C++/CLI: http://blogs.msdn.com/b/vcblog/archive/2011/03/03/1013669...
5,837,693
5,837,750
Defining a Template Member of a Template Class separately from the Declaration
#include <cstdlib> template<class A> struct Foo { template<class B> static bool Bar(); }; template<class B> template<class A> bool Foo<A>::Bar<B>() { return true; } int main() { bool b = Foo<int>::Bar<long>(); b; } This results in a linker error: main.obj : error LNK2019: unresolved external symbol...
Just reverse the order of template<class B> template<class A>. The second one is "inner" and goes with the member declaration. See §14.5.2/1. Also, as John points out, remove the parameter-list from Bar<B>. // "outer" template: this parameter gets substituted to create "inner" template template< class A > // "inner" t...
5,838,104
5,842,866
Weird compiling problem - DLL not compiled the same on some machines
I'm not asking for the SO to tell me what the problem is, I'm just asking what sanity checks should I run in a case like this. Using Visual Studio 2005, plain c++ project. Actual code is: int Sum(int a, int b) { return a+b; } No pre-compiled headers. Exported with a DEF file: LIBRARY testdll EXPORTS Sum Compi...
I suppose that "Win32 target platform" is wrong configured on your 64-bit machine. I recommend you to start "Visual Studio 2005 Command Prompt" and use dumpbin.exe /headers YouDll.dll to examine the "wrong" DLL which will be produced on the 64-bit machine. You can compare it with the "good" DLL. I suppose that you wi...
5,838,250
5,838,281
I need help with properly initlizing a structure and passing it into a function properly
I am writing a simple C++ database, using Visual Studio 2008 express edition, like program to sort and search a text file containing NCAA winners and runner ups by year, this data is to be saved within a structure. I understand how to do the sorting and searching but i am having trouble with properly initializing the ...
You have declared an array NCAAStats[Size] at the global scope. However, your functions have arguments called NCAAStats; these hide the global definition. Therefore, stuff like NCAAStats[Idx] is invalid, because that NCAAStats is a Data &, not a Data[].
5,838,287
5,838,540
How do I (C++ STL) binary_search for Abstract classes?
One can use the STL binary search algorithms (binary_search, upper_bound, lower_bound) to search a vector of Base pointers for a derived object, as shown below. Since Base is abstract (protected constructor), one has to instantiate a Derived object for the search functions, which is slightly ugly. I want to search the ...
The target of the comparison doesn't have to be the same type as the contents of the container, it just has to be something you can compare to the container: #include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { vector<int> v; v.push_back(1); v.push_back(2); v.p...
5,838,328
5,838,359
c++ _vsnprintf unexpected format string
I have a logging function that takes in a variable number of arguments and uses _vsnprintf to format them. My problem is that when I debug my OCR automation the string it returns is sent to the log, so if the file said something like this: This bitmap says %n then it would get sent to my logging function like this: v...
The traditional way to make sure something can't be expanded by printf is log("%s", yourString); Of course, you could also add a variant of log that only takes one argument, or you could count the number of variable arguments and not format the string if there aren't any.
5,838,474
5,838,513
Accessing derived objects in boost::ptr_vector
I am using a boost::ptr_vector < class A > , which I also use to store objects of class B : public class A. I want to be able to access the class B objects in the vector; how do I cast to get access?
Ideally, A should provide a virtual interface that allows you to access the parts of B that you need. If you need to access the actual B objects, you would need to use dynamic_cast on the reference yielded by an iterator into the container (you could use static_cast if you knew with certainty that the iterator actuall...
5,838,679
5,839,607
How to use std::for_each on a function pointer list
On the following code, how can i rewrite the for loop by using a std::for_each instruction. I tried to use boost::lambda::_1, boost::bind, but I could not make it working. #include <vector> #include <iostream> #include <cstring> #include <cstdlib> int main() { std::vector<int(*)(const char*)> processors; proces...
If boost::lambda and '\n' instead of endl are allowed, does the following code meet the purpose? namespace bl = boost::lambda; std::for_each( processors.begin(), processors.end() , std::cout << bl::bind( bl::_1, data ) << '\n' );
5,838,711
5,838,723
std::cin input with spaces?
#include <string> std::string input; std::cin >> input; The user wants to enter "Hello World". But cin fails at the space between the two words. How can I make cin take in the whole of Hello World? I'm actually doing this with structs and cin.getline doesn't seem to work. Here's my code: struct cd { std::string C...
You have to use cin.getline(): char input[100]; cin.getline(input,sizeof(input));
5,838,880
5,838,906
Using Ubuntu gedit to write to a file
I am trying to write a simple program that writes to a file that already exists. I am getting this error: hello2.txt: file not recognized: File truncated collect2: ld returned 1 exit status What am I doing wrong? (I tried the slashes both ways and I still get the same error.) #include<iostream> #include<fstream> usin...
There are two errors in it: hello3.txt is a string and should therefore be in quotes. std::ofstream::close() is a function, and therefore needs parenthesis. The corrected code looks like this: #include <iostream> #include <fstream> int main() { using namespace std; // doing this globally is considered bad pract...
5,838,894
5,897,892
How to build Google RE2 for Windows?
How to build Google RE2 for Windows? Somebody tried?
UPDATE: found a Windows project which may or may not work better: https://code.google.com/p/re2win/ Old answer (non MSVC): https://groups.google.com/group/re2-dev/browse_thread/thread/0665d7e6693b4adb/54bae4e315a484e3
5,838,895
5,838,908
SFINAE doesn't detect T::reference
The std::vector<T> class is a model of the STL Container concept, and as such any proper implementation of vector has to include a nested typedef value_type as well as reference. This should be detectable using SFINAE. However, in my own tests, I can use SFINAE to detect a nested value_type typedef, but for some reas...
What's a pointer to a reference? A: Impossible. Pointers to references cannot exist, so neither of your functions can exist. This is in contrast to your first case, where at least one of the functions can exist (and thus you get compilation, linkage and output). Interestingly, SFINAE is working here, as the function de...
5,838,922
5,838,998
How to delete an object in a set
In my C++ program, I create objects in one function using new. These objects are inserted into a set. When I want to remove objects from the set, I use an iterator in a for-loop. When I remove the object from the set, I still need to delete the object to free its memory, correct? I tried using delete, but then I get an...
Assuming you're calling the set's erase() method, note that this will call the destructor of the object for you. After you erase() your object, it has already been deleted, and thus your second attempt to manually call delete will fail as the pointer is no longer allocated. For reference, see this
5,838,962
5,838,979
What is an opaque byte string?
I've been gooling for a while, but I found nothing too helpful. What is an opaque byte string and what would be a c/c++ example of it ? Update A little more context, from rfc5001 2.3. The NSID Option The OPTION-CODE for the NSID option is 3. The OPTION-DATA for the NSID option is an opaque byte string, the s...
They probably mean a byte array of unspecified format. By "opaque" they mean that the inner structure exists, but is unknown. So the program is expected to treat the string as a whole - store it, transmit it, but not try to interpret. The C++ example would be an instance of std::vector<unsigned char>. A C example would...
5,839,095
5,839,207
Sample texture in GL_POINTS shaders
I have a shader that draws particles with solid colors. I would like to enable the shader to sample an FBO texture so that each particle can act upon the color "behind" it. Seems like it should be pretty simple, but no. I've simplified the code such that I would expect my FBO to be drawn on the face of every particle, ...
Instead of gl_TexCoord[0].st you need gl_PointCoord.st.
5,839,132
5,839,495
C++ How to make two programs communicate?
Question: What is the best way to make two programs (both running on the same computer) communicate and interact? (Windows, C++) Theoretical situation: On a Windows PC, I have a 3rd party software that you use to do stuff (like open/edit/save files...it's not really important). This 3rd party software has an available...
there are many solutions with many pros and cons. you will have to do some reading on each to work out which is best for you. no solution is best for everyone here is a good starting place http://msdn.microsoft.com/en-us/library/aa365574(v=vs.85).aspx
5,839,285
5,839,370
C++: Limiting CPU usage intentionally
At my company, we often test the performance of our USB and FireWire devices under CPU strain. There is a test code we run that loads the CPU, and it is often used in really simple informal tests to see what happens to our device's performance. I took a look at the code for this, and its a simple loop that increments a...
CPU quotas on Windows 7 and on Linux. Also on QNX (i.e. Blackberry Tablet OS) and LynuxWorks In case of broken links, the articles are named: Windows -- "CPU rate limits in Windows Server 2008 R2 and Windows 7" Linux -- "CPU Usage Limiter for Linux" QNX -- "Adaptive Partitioning" LynuxWorks - "Partitioning Operating S...
5,839,310
5,839,318
Using a global vector of structs
I am trying to globally declare – and initialize – a vector of structs. My code is the following: Struct creation (in header file vsystem.h) struct var { string name; float value; }; Variable (in source file vsystem.cpp) #include <string> #include <vector> vector <var> varList; Bo...
vector is in the std namespace. You need to qualify it as std::vector in your declaration: std::vector <var> varList; (Alternatively you could use a using declaration, using std::vector;, if you really hate the std::.) Similarly for string; it needs to be qualified as std::string. All of the names in the C++ Standar...
5,839,336
5,839,344
Explain bug behaviour
Can you please explain what's going on in this buggy example: Base base; Derived* d = reinterpret_cast<Derived*> (&base); d->method(); d->virtual_method(); //output: Derived-method() Base-virtual_method() I would expect this code to behave the other way around. Probably the compiler shares a single memory layout for...
base is a Base object; you reinterpret its bytes as a Derived object and then attempt to use it as if it were a Derived object. The behavior when you do this is undefined. Your program might crash; it might appear to do the right thing; it might make your computer light on fire. Note that it is never correct to use r...
5,839,357
5,839,442
Detect operator support with decltype/SFINAE
A (somewhat) outdated article explores ways to use decltype along with SFINAE to detect if a type supports certain operators, such as == or <. Here's example code to detect if a class supports the < operator: template <class T> struct supports_less_than { static auto less_than_test(const T* t) -> decltype(*t < *t...
You need to make your less_than_test function a template, since SFINAE stands for Substitution Failure Is Not An Error and there's no template function that can fail selection in your code. template <class T> struct supports_less_than { template <class U> static auto less_than_test(const U* u) -> decltype(*u < ...
5,839,362
5,839,409
Why do I get LNK4098 conflicts with use of other libs - when trying to compile C++ in MSVS2010 Express?
My program will not successfully compile in /MT (MultiThreaded) mode. It Compiles in /MD (MultiThreaded DLL). I want to be able to use both libcurl and boost in an application I will distribute with an installer. Compiling in: MSVS2010 This is code to replicate my problem: #include "stdafx.h" #include "boost/regex.hpp...
Try setting nodefaultlib:libcmt.lib in linker options in VC.
5,839,499
5,839,609
C++ copying a string array[] to a vector <string>
So i'm making this class with a member function "insert" to copy from a string array to the classes contents which is a vector array. This abort error keeps popping up saying i'm going past the Vector end, but i don't understand why.... Here's the code: /////////////////////////////////////////////////////////////////...
Actually, you don't need copy them yourself. You can use std::vector::assign to convert a c-style array to an std::vector. vector::assign Assigns new content to the vector object, dropping all the elements contained in the vector before the call and replacing them by those specified by the parameters. Example string sA...
5,839,503
5,839,520
Different symbols used in VC++
Possible Duplicate: When do I use a dot, arrow, or double colon to refer to members of a class in C++? Various examples that I see, I've seen them use ::, -> and . . I usually get confused between the last 2. Can someone help me making it clear about the usage of -> and . in VC++ about where can I use it and what is...
-> dereferences the pointer to its left. . uses the object to its left which is not a pointer.
5,839,536
5,841,095
How can I set member property as tooltip for QGraphicsItem?
I set the item name as the tooltip for QGraphicsItem by default. But in my program, users can change this item name, so I want to show the correct tooltip after they change the name. But setToolTip() only accept const QString, is there any way to accept a dynamic changing member property as input? I do not want to just...
Sice you can always get the updated item name, you can add a signal which gets emitted whenever there is a change in the item name and connect this signal with a slot which can be used to set the tooltip to the updated item name along with other member properties you would like to set it to. Hope this helps.
5,839,654
5,839,686
Should I use both header files and cpp/source files?
I have a Mammal.h file that reads: #ifndef MAMMAL_H #define MAMMAL_H class Mammal { public: void Speak(); }; #endif My CPP file looks like: #include "stdafx.h" #include "Mammal.h" #include <iostream> void Mammal::Speak() { using namespace std; cout << "Speaking"; } And my use of this code is seen here...
Try calling that code from more than one place -- and therefore #including the header in more than one source file -- and you'll see the problem in the second approach. The linker doesn't like it if you have more than one definition of the same function, even if they're identical.
5,839,656
5,839,719
How to initialize a multi-dimensional array in a C++ constructor
I have a class that contains a few multi-dimensional arrays. I am trying to initialize these arrays in the constructor, but I am having trouble figuring our how to do it. The array is always of a fixed size. Here's what I have so far: class foo { private: int* matrix; //a 10x10 array public: foo(); foo...
#include <memory.h> class foo { public: foo() { memset(&matrix, 100*sizeof(int), 0); } private: int matrix[10][10]; }; That is, if you're not binding yourself to doing it with pointers (otherwise you can just pass in the pointer to memset, rather than a reference to ...
5,839,694
5,840,319
How to avoid stack overflow in deep tree recursion
I've read many similar articles, I apologise if this has already been answered, but I'm still stuck. I'm coding a function to populate a tree, each node having four branches, which will store the possible manipulation of states of the "eight tile puzzle" i.e. http://www.8puzzle.com/images/8_puzzle_start_state_a.png Th...
This is a very generic answer, but have you tried to explicitly manage your stack through something like a heap allocated queue or a stack? Basically don't use actually function calls, just push and pull things off your own stack/queue. They cover non-recursive graph traversal algorithms here (both depth first, and b...
5,839,902
5,839,914
how do you use the terminal on mac os 10 to write and compile c++ code?
how do you use the terminal on mac os 10 to write and compile c++ code? I have a power mac with the power pc chip/with leopard.
First, make sure you've got Apple's developer tools installed. They may be on your Mac OS X install disk as well, if you don't feel like downloading. (although you may get an older version) After that, cd to where your code is and do something similar to this: g++ -o my_executable my_cpp_code.cpp You can then run it l...
5,839,920
5,839,944
how to convert this to C#
Hi i have the following code which i would like to convert to C#. Could you share some light here how can i convert those to C#? i am not well familiar with C++. Especially on the function DeviceIoControl which it is calling the WinBase API. In C#, what function should i use to replace DeviceIOCOntrol? shareMode = FILE...
You must use P/Invoke interop to access DeviceIoControl. Here is a link that has similar calls and should be a good starting point: Defrag API C# wrappers
5,839,998
5,840,008
what is sprintf in c#?
what does this c++ code look like in c#? sprintf(ff, "\\\\.\\%s", device);
string ff = string.Format("\\\\.\\{0}", device); or, better yet: var ff = string.Format(@"\\.\{0}", device);
5,840,064
5,840,081
Why doesn't make work on a C++ compile with a reference address pointer?
I am a computer science student and taking my first C++ class. I have a problem understanding what is going on with my code: // This program uses the address of each element in the array. #include <iostream> using namespace std; int main() { const int NUM_COINS = 5; int coins[NUM_COINS] = {5, 1, 25, 5, 10}; ...
Reason: You are not using the comparision operator correctly. After changing it to be "<", your code should work correctly. for(count = 0; count << NUM_COINS; count++) ^ should be "<" here
5,840,148
5,840,160
How can I get a file's size in C++?
Let's create a complementary question to this one. What is the most common way to get the file size in C++? Before answering, make sure it is portable (may be executed on Unix, Mac and Windows), reliable, easy to understand and without library dependencies (no boost or qt, but for instance glib is ok since it is portab...
#include <fstream> std::ifstream::pos_type filesize(const char* filename) { std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary); return in.tellg(); } See http://www.cplusplus.com/doc/tutorial/files/ for more information on files in C++. edit: this answer is not correct since tellg() does n...
5,840,323
5,840,332
C++ | Syntax Error: Identifier 'i'
Hey guys, I'm pretty sure someone else has had this problem too, but I just couldn't find any related problems. This is also probably something really stupid like a typo or something, but I'm not able to figure it out >.< What's wrong with the code, I always get this error: error C2061: syntax error : identifier 'i' #i...
You need to enclose the conditions in parentheses. In other words, change this: } while i > 100 || i < 0; To this: } while(i > 100 || i < 0);
5,840,402
5,841,127
how to parsing of xml in mosync ide
i am sending a request to server and receive an response as an form of xml but i want to parse it so which method i should prefer...
If your question is "How to parse XML" just use something simple as eXpat (SAX parser) or plug into something more sophisticated like Xerces (SAX & DOM parser) or libxml2. From your headline it seems you are using mosync, which already provides XML parsing http://www.mosync.com/documentation/tutorials/processing-xml If...
5,840,421
5,840,502
How to prevent an object from being deleted in places where it shouldn't, at compile-time?
I have classes Graph and Algorithm: class Graph { ... }; class Algorithm { ... private: Graph * mGraph; ... }; I want my algorithm to be able to do everything with mGraph except deleting it. I.e. I want to detect (at compile time) if somewhere in algorithm I'm deleting the graph. Is there a good (elegant) way to do s...
As others have pointed out, you cannot guard against malicious users of Graph. I'll assume that you don't want to, either, and that you're in the position of the Graph author trying to prevent users of the class from misunderstanding the ownership semantics of Graph while implementing Algorithm(s). You could hand out o...
5,840,462
5,840,573
Qt- How to use connect between incompatible signal and slot
I am trying to do a game. In this I want to call a function, that function will receive a point . But this function should be invoked by a timer's timedout signal. Can anybody say how to achieve this. Below is the required/error code Point p(a,b); connect(timer,SIGNAL(timedout()),this,startDestruction(p)); Can anyb...
Create a method to use as an intermediate slot, like this. Point p(a,b); connect(timer, SIGNAL(timedout()), this, q); q() { startDestruction(this->p) }
5,840,616
5,840,635
c++, List all files, dirent.h on Windows
in C++, what would be the best way to list all files of a directory on Windows? On Linux or on Windows using gcc (e.g. MingW) this is easy possible with dirent.h, but what's the best way to do it on Windows when dirent.h is not available (e.g. Visual Studio)? Should I force people do add a freely available implementati...
Something like Boost Filesystem would work across all of those situations.
5,840,692
5,840,934
why does the below code compile successfully in VS2010?
I have the below exception class. class ExceptionTest : std::exception { public: ExceptionTest(int value): m_value(value) { } ~ExceptionTest() { } private: ExceptionTest(const ExceptionTest& test) { } int m_value; }; I then use it in this way - int checkexception() { throw ExceptionTest(2); } int main() { try { ...
This appears to be an error in VS2010's C++ implementation. When you throw an expression a temporary exception object is created by copying (or moving) the operand of the throw expression. If the expression has class type this involves the copy (or move) constructor and the constructor must be accessible at the point o...
5,840,939
5,841,517
Comparison function for sorting member vector with sort()
i have a class like this: class test { vector<expr*> _exprs; bool cmp(expr* e1, expr* e2); ExprManager* mg; } and the Comparison function is: bool test::cmp(expr* e1, expr* e2) { return exprHight(mg, e1) < exprHight(mg, e2); } then when i use the comparison function in sorting the...
The normal way to define a predicate for sorting is as a functor. Make your class define the operator() to do the comparing, and you can just pass an instance of the class to std::sort. So really, all you need to do is to define the class like this instead: class test { vector<expr*> _exprs; bool operator(...
5,840,972
5,841,027
Why is the extraction operator not working?
I trying out some problems in Google's Code Jam. For the question Store Credit, I have the following code in C++: if (input.is_open()) { getline(input, line); ss << line; ss >> nCases; for (int i = 0; i < nCases; i++) { getline(input, line); ss << line; ss >> credit; ...
Instead of ss << line;, reset the stream with ss.str(line); ss.clear();
5,840,977
5,841,017
OpenGL Polygon Render order
As you can see: http://i.stack.imgur.com/ztM0v.png, certain polygons are simply being rendered over the other ones. Does anyone have any suggestions or related reading on rendering these in the correct order so that they do not overlap?
For opaque faces render order is not important as long as you use the depth buffer. NeHe has a tutorial covering all the basics. Start here http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=02 See also Opengl Depth buffer and Culling and Depth Buffer in OpenGL .
5,841,000
5,841,029
Problem with multiplication of signed chars
Discussing this answer I find out that the code bellow prints -1 and 1 in visual studio. Why? In my opinion it should print two 1s despit overflow during multiplication. signed char c1 = numeric_limits<signed char>::min(); signed char c2 = -1; cout << c1 * c2 / c1 << endl; signed char result = c1 * c2; cout << result /...
c1 might have a value like -128, say. In the multiplication, integer promotions will cause both c1 and c2 to be converted to type int before the operation is performed. c1 * c2 is then going to be a int with value 128 so c1 * c2 / c1 is going to be an int with value -1. -1 for the first output looks correct to me. For ...
5,841,038
5,841,126
cvHoughLines2 memory leak
Does OpenCV method HoughLines2 has a memory leak that's not been fixed since now (version 2.1.0.6), or there's something wrong with this part of my code ? CvMemStorage *storage = cvCreateMemStorage(0); CvSeq *linesSeq = 0; double smallL = 0.0, bigL=0.0, smallA = 0.0, bigA = 0.0; linesSeq = cvHoughLines2(cannyImg, stor...
You are using cvClearMemStorage. This does not deallocate memory, it just resets some pointers. If you want to release the memory, you should use cvReleaseMemStorage(&storage) (and you wouldn't need cvClearSeq anymore, by the way, since you would deallocate memory).
5,841,077
5,841,119
resizing c++ vectors without calling their constructors
So I have this situation where I have: std::vector<Coord3D> thevector; where Coord3D is just a simple struct with 3 floats: x, y and z. The constructor also only simply has x = 0; y = 0; z = 0; etc. Now, suppose I want to append the contents of another vector into thevector. Is it possible to resize the vector's size ...
thevector.insert(thevector.end(), theothervector.begin(), theothervector.end()); If Coord3D are bitwise-copyable the compiler should be able to optimize it to the same code as memcpy.
5,841,111
5,841,242
RPC lib in multilanguage
I search for RPC lib that support client or server in C++ and C#. So i can make client in C++ and talk to server written in C#. I do not know if Microsoft RPC allow this, Protocol Buffers or MsgPack.
Apache Thrift provides a mechanism for defining "services" in any language and accessing that service. There are resources for developing services in both c++ and c#: c++: http://wiki.apache.org/thrift/ThriftUsageC%2B%2B c#: http://www.markhneedham.com/blog/2008/08/29/c-thrift-examples/ Alternatively, although it's not...
5,841,155
5,841,169
Creating Array of Classes
I got a class such as: class me362 { public: void geometry(long double xLength); void mesh(int xNode); void properties(long double H, long double D, long double K,long double Q, long double DT,long double PHO,long double CP, long double TINF); void drichlet(long double TLeft,long double TRight); voi...
Use std::vector, which handles dynamic memory for you: #include <vector> // ... std::vector<me362> domains; std::vector also has a lot of nice features and guarantees, like being layout-compatible with C, having locality of reference, zero overhead per element, and so on. Also note that std::vector has a constructor...
5,841,439
6,059,410
View array in Visual Studio debugger?
my question is not a duplicate of this the solution provided in the above does not work when using Nsight as a debugger. how can i view all the elements of an array inside a kernel when using Nsight as a debugger? QuickWhatch only shows the first 4 elements of the array!
The number of elements NSight will copy to the host for debugging is set in: Nsight->Nsight Options->Debugger->Max Array elements The default is 4, which is why you only see 4 elements. Increase this (and restart your debugging session), and you will be fine.
5,841,516
5,841,528
Embedding WinMain entrypoint into a class?
I was wondering, is it possible to use the entry point of a win32 program - the WinMain - as a class method? For example; class cApp { public: cApp(); ~cApp(); cGuiManager* guiManager; cServerManager* serverManager; cAudioManager* audioManager; int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE h...
No. WinMain cannot be a member of class as "entry" point of the program. And for that matter, WinMain cannot be in any namespace (other than the global namespace). For example, even user::WinMain as shown below cannot be the "entry" point of the program. namespace user { int WINAPI WinMain(HINSTANCE, HINSTANCE, LP...
5,841,555
5,841,586
C++ going from one part of the program to another
So here is my problem. I have a program that has 11 functions. I want to call one function from another but I want that function to be execute from somewhere in the middle? Any suggestions how can this be done? goto function is a very bad habit so I don't want to use it. EDIT: I initialize the variables first with loa...
It's not possible to execute from somewhere in the middle of a function that you call. Functions are things that you can call, hence the starts of functions are the places that a call can start executing from. Change this: void function1() { do_something; // <-- I want to start here do_something_else; } In...
5,841,734
5,870,833
Getting the ID of a double clicked item
Is it possible to get the name of a double clicked item i.e tables listed in QTableView by their table names?.
Yes there is. The QTableView emits the doubleClicked( const QModelIndex &index ) signal and with that you can get the name using the data( index, role) method.
5,841,903
5,841,985
Linked list with different elements , possible?
Hya, Lemme explain my point. template<typename T> class node{ T data; template<typename X> node<X>* right; // can point to any node<typename> i know its wrong } so that i can do something like: node<int> a; a.data = 23; node<float> b; b.data =43.6; a.right= b; std::cout<< a.data <<a.right->data; Another exampl...
It isn't really possible to do what you want because when using templates you have to know the types involved at compile time. In contrast, walking a previously constructed linked list requires you to discover the types in the list at runtime. To illustrate, consider this: struct node_base { virtual ~node_base() {}...
5,841,942
5,841,982
Binding with parameters
I have problem with binding parameters to function. Invoker class call function and it doesn't know about parameters. So I can't use placeholders in binding like: v.invoke(boost::bind(&B::fun, this, _1)); I want to make something like this: v.invoke(boost::bind(&B::fun, this, fun_p)); I need it because I want to pass...
Good question! You have two problems here. Problem 1: when passing a bind as a parameter to bind, you get a function composition: the result of the inner bind is evaluated and passed to the outer bind as a parameter. See the documentation. To solve this problem you should wrap your function parameter with protect: tem...
5,841,992
5,842,103
C++ array in header file
I am doing a training exercise and am having trouble getting started on it. I have to write a program for an array data structure. There is a test harness provided and I need to implement the code for the data structure. I am not sure how to define an array in a header file bellow is the test harness main.cpp which i c...
I'm pretty sure YOU are supposed to create the ArrayIntStorage.h header AND implement the matching ArrayIntStorage.cpp. Based on the "// sort data structure using std" comment you are expected to use and create a wrapper over an appropriate stl container, something like std::vector. Based on the "// do not read sort" c...
5,842,124
5,903,082
Can Qt signals return a value?
Boost.Signals allows various strategies of using the return values of slots to form the return value of the signal. E.g. adding them, forming a vector out of them, or returning the last one. The common wisdom (expressed in the Qt documentation [EDIT: as well as some answers to this question ]) is that no such thing is ...
OK. So, I did a little more investigating. Seems this is possible. I was able to emit a signal, and receive value from the slot the signal was connected to. But, the problem was that it only returned the last return value from the multiple connected slots: Here's a simple class definition (main.cpp): #include <QObject...
5,842,184
5,842,199
Is it possible to use default arguments and a variable number of arguments in a single function?
For example, something like this: #include <cstdarg> void my_function(int it=42, ...) { /* va_list/start/arg/end code here */ } What exactly does the above code mean in C++? It compiles fine in G++. Note, I can't imagine any scenario where this would be useful or even what it ought to do. I'm just curious.
void my_function(int it=42, ...) You said this function compiles fine with GCC, but you cannot make use of the default argument, you will have to pass argument for the so-called default parameter as well, to work with this function. my_function("string", 98, 78, 99); //error my_function(898, "string", 98, 78, 99); //o...
5,842,235
5,898,792
linux/videodev.h : no such file or directory - OpenCV on ubuntu 11.04
I tried to install OpenCV2.2 on Ubuntu 11.04. But OpenCV compilation fails stating an error related to linux/videodev.h file. File available in /user/includes/linux is named videodev2.h. /home/user/OpenCV-2.2.0/modules/highgui/src/cap_v4l.cpp:217:28: fatal error: linux/videodev.h: No such file or directory compilat...
sudo apt-get install libv4l-dev Editing for RH based systems : On a Fedora 16 to install pygame 1.9.1 (in a virtualenv): sudo yum install libv4l-devel sudo ln -s /usr/include/libv4l1-videodev.h /usr/include/linux/videodev.h
5,842,369
5,842,385
Need help to convert
Hi i have tried to convert the c++ code below to c# but i don seem to get it right. I got this below in .h header file public: unsigned char inquiry_data[256]; Then the .cpp file sa = (PSCSI_ADDRESS)&inquiry_data[0]; When i Go Definition of the (PSCSI_ADDRESS) i got this below: typedef struct _SCSI_ADDRESS { ULO...
For a start, that C++ code is relying on undefined behaviour. You cannot cast arbitrary sections of memory to complex types and then attempt to access them. C# does not allow arbitrary casts like that. If you are interested in turning raw bytes into data, you want to look into C# serialization.
5,842,583
5,842,597
C++ pass variable from .cpp to header file
this relates to a question i asked previously: C++ array in header file in the main.cpp file there is a variable called fin1 ifstream fin1("ACW2_data.txt"); this might be a stupid question, but how can i use the value of this variable from main.cpp in the header file? (ie. is there a way to pass variables between the ...
This variable can be declared in the header file as an extern. extern ifstream fin1; Now you can use this variable wherever you #include this header file including the header file itself. You don't need to pass the variable as such. :)
5,842,637
6,045,282
Using Apache Thrift in Windows
I'm interested in compiling Thrift-generated code and linking to the thrift C++ library in a windows environment. Doing some research, I found a few recent links: 1) Thrift Win32 Installation Using Cygwin/MinGW 2) THRIFT-1031 and THRIFT-1123 patches to compile in MS Visual C++ Using #1, I was able to compile a linux li...
There´s a patch available to copile the thrift runtime with visual studio c++. It would be great if the thift developers put this patch in the main code. https://issues.apache.org/jira/browse/THRIFT-591
5,842,647
5,842,679
Compare iterators, C++
Is it possible to compare two iterators? A comparision using std::min void change ( typename TList <Item *>::Type ::iterator it_begin, typename TList <Item*>::Type ::iterator it_end ) { .... this->items.resize ( index ); std::sort ( it_begin, std::min (it_end, it_begin += index - 1); //Compare two iterators, exce...
Yes. But I doubt if you can do that with std::min. You can use std::distance function to calculate the distance between two iterators. And then you can use the distance to determine which iterator is the smaller one. Once you know the smaller iterator, you can pass that to std::sort function. Here is small illustration...
5,842,737
5,842,754
Garbage Collection in C/C++ versus Java
There is no Automatic Garbage Collection in C/C++. Assume that I wrote a simple program in C/C++ and created a single object. Assume that there are exactly 10 or extremely limited number of addresses for allocation. I have a for loop running for 100 times inside which this single object is created every time the loop i...
C++ doesn't have (built-in) garbage collection, but that doesn't mean you should let your dynamically allocated memory stay allocated forever. You can and should free it. The most basic way to that would be to free your object reference (or pointer, since this is C++) manually when you don't need it anymore: for(int i ...
5,842,771
6,858,651
Activate previous process on Mac
Is it possible to determine the previous active process to activate it? Mac OS X / C++ / Carbon. GetNextProcess() does not refer to Z-order of processes, but I need the real previous. The original task is to bring the user back to their work when they closes my info window. Currently another window of my app gets the ...
You can get the zorder of processes from this place. Last process should be the one you are looking for. Or change code to read in reverse.
5,842,783
5,842,812
what is the overflow tool in C language?
During a interview, I was asked what kind of overflow tool in C language you used? I do not know any tool like that. And in C++, what kind of tool used to track the versions of c++ files? Do anyone know about that?
I assume that "overflow" in this context is referring to "buffer overflow". There are a range of memory debuggers available, that can detect this kind of error. One popular example is Valgrind. Tracking file versions is generally done with a revision control system (RCS), but this isn't specific to C++. There are zi...
5,843,151
5,843,246
Advice on how to use Qt Model View classes
So I have been writing a Sudoku game in C++. I have most of the game logic done and tested, but I wanted to use Qt on top of it for the GUI. I was trying to figure out the best way to work with the Qt classes for my needs. As a test, I played around with QAbstractTableModel. I subclassed it and had it access my exis...
You have two options: Continue to use QTableView and your QAbstractTableModel, and subclass QStyledItemDelegate to render the cells exactly how you want them. You can't change the inter-cell painting that way, though. Note, however, that you can achieve a lot of what you want (fonts, colors) by reacting to more Qt::It...
5,843,594
5,843,617
problem with calling libraries
hi i'm watching a c++ tutorial and instructor includes the libraries like this # include "map.h" #include "set.h" but when i use this code i get error fatal error C1083: Cannot open include file: 'set.h': No such file or directory so i have to write it like this # include <map> #include <set> but now i ha...
Pretty obviously, your tutorial doesn't use the Standard Template Library, and uses a custom library of its own. #include "set.h" looks for a set.h file in the user search path, which is usually the current directory. Since you don't have the file, the compiler emits an error. When you #include <set>, you get the STL s...
5,843,881
5,843,891
for_each weird behaviour
I don't use the STL much and I'm wanting to start learning it, so I made a really simple program using the STL's for_each function. Here is the entire program (minus header files): class Object { public: int s; Object() : s(0) { } Object(const Object& rhs) : s(rhs.s) { } void operator() (int a) { ...
for_each works with a copy of the functor that you provide, and then returns a copy at the end. You need this: sum = for_each(arr, arr + sizeof(arr) / sizeof(int), sum);
5,843,895
5,843,918
String Concatenation with Integers
Damage and Cost are integers, but as you can see in the code below I want to concatenate them with a string (if that's the right word). How can I do this? class Weapon : Shopable{ private: int Damage; public: std::string getDesc() const{ return getName()+"\t"+Damage+"\t"+Cost; ...
Provide yourself with this template: #include <sstream> template <class TYPE> std::string Str( const TYPE & t ) { std::ostringstream os; os << t; return os.str(); } You can then say: return getName() + "\t" + Str( Damage ) + "\t" + Str(Cost); Note this is pretty much equivalent to Boost's lexical_cast, a...
5,844,036
5,844,182
QList children - struct or custom classes derived from QObject?
I'm currently working on Qt application on Symbian platform. Application has an sqlite database and initial data is populated from txt files. I'm implementing online update from data that comes in json format. So i would like to create generic functions in my db update class that takes QList of classes/structs and u...
That depends on whether your classes are carrying behaviour or only state. They carry behaviour. Then, a polymorphic class is in order, yes. Whether it needs to inherit from QObject is another question. Inherit from QObject only if you need its services (introspection, signals/slots, event handling). Otherwise, don't....
5,844,070
5,844,171
Firefox interacts with my timers ?! (followup)
First please read my older post in which I thought I fixed it. (skip if you don't have time) Firefox interacts with my timers somehow ?!?! This is crazy ^^ For those who do not want to read, I'll just sum it up: Firefox messes my timers when it is running so I had to switch from timeGetTime() to QueryPerformanceCounter...
How are you calculating motion? If you accurately calculate delta-time (the time since the last tick) with QueryPerformanceCounter, and calculate motion based on that, you should be fine. So the distance each object moves per tick should be deltatime * speed. My best guess is you're not doing that, and instead it's b...
5,844,184
5,844,212
Wrong output C++ ArrayList
When i make ArrayList with size 5 it gives wrong result but when it becomes bigger than 5 it becomes correct! #include <iostream> #include <string> using namespace std; class list { typedef int ListElemtype; private: ListElemtype listArray[6]; public: bool insert(ListElemtype e) { if (numberOf...
Arrays are indexed from zero, not from one. So listArray[numberOfElements+1]=e; should be listArray[numberOfElements]=e;. The first inserted element goes into listArray[0].
5,844,197
5,844,434
C++ copy text file program using header file
Hello i am making a program that is supposed to copy a text file. The text file is just 3 lines of text at the moment. The textFileCopy function is supposed to read in a text file given by the filenamein array and then output a copy of the text file given by the filenameout array. This is my main.cpp file. In this file...
textFileCopy(false, false) is being implicitly converted to textFilecopy(NULL, NULL) and when you attempt to open an ifstream with a NULL filename, you get the assertion you're seeing.
5,844,315
5,844,350
Building an Object System Around shared_ptr
I am using shared_ptr as my garbage collection for a toy language that I am working on which compiles to C++. My objects derive from a common base class above that there are strings and numbers then there are vectors and maps. Everything on the c++ side is passed wrapped in shared_ptrs so my containers actually hold s...
Here's how I'd set this up: namespace toylang { class Object; // main handle type; use this for all object references // replace with boost::intrusive_ptr or similar if too inefficient typedef std::shared_ptr<Object> obj; class Object { // whatever }; class Number : public Object { int x; // etc }; clas...
5,844,332
5,844,455
value of function in c/C++
Possible Duplicate: How does dereferencing of a function pointer happen? If we have void f() { printf("called"); } Then the following code will result in output of "calledcalled": f(); (*f)(); I don't really understand how this works…what is the difference between *f and f? And why would you call a function us...
There are two ways to call a function in C++: By name: f(); Through a function pointer: typedef void (*fptr_t)(); fptr_t fptr = &f; (*fptr)(); Now, using the address-of operator on a function name (&f) obviously creates a function pointer. But the function name can implicitly convert to a function pointer when certa...
5,844,352
5,844,367
How to loop program so it continues execution
I currently have this code #include <iostream> #include <curl.h> #include <windows.h> #include "boost\timer.hpp" int main(void) { CURL *curl; CURLcode res; boost::timer t; int number = 1; while (number == 1) { if(t.elapsed() > 10) { curl = curl_easy_init(); ...
You can use Sleep(10000) to pause program execution for approx. 10 seconds. You can drop the boost::timer - just sleep 10 seconds in each loop iteration (Sleep is not as accurate, but for 10 seconds the inaccuracy should be negligible). Your code is what is called a 'busy loop' - for the CPU it makes no difference whet...
5,844,428
5,844,445
Pthread_create fails after creating several threads
I'm developing an application which handles client connections. I'm spawning a thread for each request, since there will be short tasks. However, I keep having a problem after handling a certain amount of connections. Specifically, after 381 connections, pthread_create fails to create a new thread. I know this can fail...
If you do not call pthread_join or detach the thread (either by calling pthread_detach or creating it in the detached state using attributes), the resources used by the terminated thread will never be freed. This is your problem. If you don't need to join your threads, detach them as soon as you create them.
5,844,429
5,844,460
_bstr_t concatenate gives 12142
I have a strange thing here. I'm concatenating _bstr_t strings in order to assemble a SQL command. _bstr_t strSQL = a+b+k+hk+Allin+hk+k+hk ...and so on. When I print it to the console (using std::wcout << '/n'<< strSQL << '/n';) I get my string, BUT with a 12142 in the beginning and end of the string. It looks like...
You wrote '/n' instead of '\n'. This is a multicharacter literal, which in this case gives an integer with the value 12142.
5,844,446
5,844,468
Visual C++ assertion failure
I am creating a program to copy a text file. I have a main.cpp file which reads in a text file given by the filenamein array and then output a copy of the text file given by the filenameout array. i have this function declared in my FileUtilities.h as bool textFileCopy(char filenamein[], char filenameout[]); Then the ...
Where's the error? On fin or fout? Check the corresponding filenameXX, it must not be NULL
5,844,471
5,844,480
How is this private data member of a base class being accessed by a derived class?
I have a private data member called balance in a base class called bankAccount. I wanted my derived class checkingAccount to be able to use balance so I made it protected but i've noticed that my derived class seems to be able to still access balance even when it is put in the private section of my base class. I though...
checkingAccount::applyTransaction doesn't see or touch the base class's balance member. It's using, resetting and returning its own balance argument.
5,844,491
5,844,558
Function returns std::wstring = NULL;
I have trying to make wrapper for winapi function GetWindowText. Function returns std::wstring but i don't know how to handle where error happen. I return NULL but i know it's wrong. std::wstring GetWindowText(HWND handle) { const int size = 1024; TCHAR wnd_text[size] = {0}; HRESULT hr = ::GetWindowText(ha...
As an alternative to exceptions you could also return the string by reference in the argument list and indicate sucess by returning true or false i.e. bool GetWindowText(HWND handle, std::wstring& windowText) { const int size = 1024; TCHAR wnd_text[size] = {0}; HRESULT hr = ::GetWindowText(handle, ...
5,844,536
5,844,604
How to compare a string with certain words and if a match is found print the whole string
I am trying to write a little program that will load in a file, compare each line with a specific array of words, and if that line has any of those words in it then I want to "print" that line out to a file. My current code is: int main() { string wordsToFind[13] = {"MS SQL", "MySQL", "Virus", "spoof", "VNC", ...
If I understand your problem correctly, you want to check if the line contains one of the word and print it if it does. Right now what you are doing is this: if(firewallLogString == wordsToFind[i]) Which checks if the string exactly matches the word. So, if the string contains one of the word but has other words in it...
5,844,584
5,844,609
Class inheritance: Function is inaccessible
I'm getting this error, but I thought I would only get it if the member's protection level was too high and made it inaccessible, but I'm getting it anyway. Shopable.h: #ifndef _SHOPABLE_H_ #define _SHOPABLE_H_ #include "Library.h" class Shopable{ private: std::string Name; int Cost; std::string Descript...
You want public inheritance: class Weapon : Shopable should be: class Weapon : public Shopable Also, names like _SHOPABLE_H_ are illegal in user written C++ code, as they are reserved for the C++ implementation. Forget the leading underscores and use SHOPABLE_H. And: Weapon(int Cost,int Damage,std::string Name) ...
5,844,657
5,844,666
Splitting a c++ string into two parts
I'm trying to split a string that contains "|" into two parts. if (size_t found = s.find("|") != string::npos) { cout << "left side = " << s.substr(0,found) << endl; cout << "right side = " << s.substr(found+1, string::npos) << endl; } This works with "a|b", but with "a | b", it will have "| b" as the right ...
size_t found = s.find("|") != string::npos This is a declaration; it gets parsed as size_t found = (s.find("|") != string::npos) So, found will always be 1 or 0. You need to declare found outside of the condition and use some parentheses: size_t found; if ((found = s.find("|")) != string::npos)
5,844,689
5,844,757
WinAPI: How to process keyboard input in custom edit control
So i'm creating my own edit control (multi-line textbox) in C++ using the windows API. It's going pretty well, but i'm a bit confused about one thing. First off, the control is being built to be able to handle unicode and all input will be converted to unicode. In other words, all input will be stored as wchar_t. What ...
If your control is created as a unicode window (using CreateWindowW) then in WM_CHAR you will get wide char out of the box. If you want to provide non-unicode version of your control then you need to handle WM_INPUTLANGCHANGE, something like this: case WM_INPUTLANGCHANGE: { HKL NewInputLocale = (HKL) lPa...
5,844,861
5,845,150
Word Solver - All Directions
I created a word solver for all directions. It finds words horizontally, vertically and reverse. However, I am having problems making it go all directions. So to take "hello" in: H E i l x L p q c L O m Anyone can point me on how to do that? Here is my algorithm to that searches for the words (in C++): /* * ...
1) Currently, your solve() function looks for a word in a straight line starting at each point: is this what you intend? I only ask because 'hello' doesn't appear as a straight line in your sample matrix: H E i l x L p q c L O m If you do want straight-line words only, then fine (this is how I've always under...
5,845,064
5,846,113
Help Converting Math function into Code : Linear Kalman Particle Swarm Optimization
I'm trying to convert the math presented on this paper: http://www.bouncingchairs.net/pskalman-lategecco.pdf Around page 3 forward into working code. The algorithm itself is given around page 6, but I don't speak greek or math; so for the time being I'm stuck. If I understand the code, it should run down like this: ...
I think you might be missing the calls to "norm(...)". Normalizing a vector is just dividing each component of the vector by the length. In Equation 9, they calculate the weighted sum of the lengths of vt and vbest and multiply that average length by norm(vbar). You're just multiplying it by vbar directly. The intent b...
5,845,151
5,845,496
How to make this pipe work in c++?
I am programming a shell in c++. It needs to be able to pipe the output from one thing to another. For example, in linux, you can pipe a textfile to more by doing cat textfile | more. My function to pipe one thing to another is declared like this: void pipeinput(string input, string output); I send "cat textfile" as ...
Take a look at popen(3), which is a way to avoid execvp.