ArkM 1,090 Postaholic

1. Use icode (not code) tag for inline codes.
2. Strictly speaking, bad position value of sttring::find is

const size_t badpos = std::string::npos;

3. Use string output directly, w/o c_str():

cout << windowName;

There is overloaded operator << for std::string.
4. Probably, the memory is corrupted and windowName value is not a valid std::string value. Why? It's the other question, the error context needed...

ArkM 1,090 Postaholic

wow ArkM that function is like sent from god himself lol it worked fantastic, is there anywhere i can learn about all these long pointer string and stuff cuz they just dont make any sense to me and there used alot in windows programing

Well, God talks with us via other people...
I was glad to help you.
The best knowledge base? MSDN, of course...
Don't forget to set a proper (national) code page.
Good luck!

ArkM 1,090 Postaholic
bool cvtLPW2stdstring(std::string& s, const LPWSTR pw,
                      UINT codepage = CP_ACP)
{
    bool res = false;
    char* p = 0;
    int bsz;

    bsz = WideCharToMultiByte(codepage,
        0,
        pw,-1,
        0,0,
        0,0);
    if (bsz > 0) {
        p = new char[bsz];
        int rc = WideCharToMultiByte(codepage,
            0,
            pw,-1,
            p,bsz,
            0,0);
        if (rc != 0) {
            p[bsz-1] = 0;
            s = p;
            res = true;
        }
    }
    delete [] p;
    return res;
}

int main()
{
    wchar_t msg[] = L"Hello, world!";
    std::string s("\?");

    cvtLPW2stdstring(s,msg);
    std::cout << s << std::endl;

    return 0;
}

It's possible to add more parameters check ups...

ArkM 1,090 Postaholic

Are you sure you added the library files from project settings?

IMHO, it's of no importance: there are obviously misspelled SDL function names in the source...

ArkM 1,090 Postaholic

Read SDL tutorials carefully then correct misprints in you sources. Must be SDL_DisplayFormat, SDL_SetVideoMode etc...

ArkM 1,090 Postaholic

Practically all modern DBMS (may be except some OODBMS) have C interfaces (direct or via ODBC).
Try MySQL, for example...

ArkM 1,090 Postaholic

I don't like this approach, but...

template <typename C>
typename C::iterator SlowFind(C& c, const typename C::value_type& v)
{
    typename C::iterator i;
    for (i = c.begin(); i != c.end() && *i != v; ++i)
        ;
    return i;
}

typedef std::vector<int> Vector;
typedef std::list<int> List;
using std::cout;
using std::endl;

int main()
{
    Vector iv;
    iv.push_back(1);
    iv.push_back(2);
    iv.push_back(3);
    Vector::iterator vi;
    vi = SlowFind<Vector>(iv,2);
    if (vi != iv.end())
        cout << *vi << endl;

    List il;
    il.push_back(1);
    il.push_back(2);
    il.push_back(3);
    List::iterator li;
    li = SlowFind<List>(il,3);
    if (li != il.end())
        cout << *li << endl;
    return 0;
}
ArkM 1,090 Postaholic

It seems you don't understand C++ syntax and flow of control semantics.
For example, the if statement selects one of two alternatives:

if (condition) {
   do it (if condition true)
   as usually there is a sequence of statements here
}
else {
   do that (if condition false)
   ...
}

For example:

if (wheelNumber == 0) // wheelNumber is zero)
{
    
   //Add ZERO_WIN_AMOUNT to Money Remaining
   moneyRemaining += ZERO_WIN_AMOUNT;
}
else // wheelNumber is not equal to zero
{
    // Add BET_AMOUNT to Money Remaining
    moneyRemaining += BET_AMOUNT;
}

There are lots of other misunderstanded C++ constructs in your code. For example, fantastic:

((moneyRemaining += ZERO_WIN_AMOUNT) && (moneyRemaining += bet));

No special assignment statements in C++. The simplest statement is so called expression statement:

any_expression ; // semicolon is a part of an expression stmt: terminator

No need to enclose every expression in parentheses: both expression and (expression) have the same effect.
Look at your expression now. It has a form expression1 && expression2. The && operator has two operands. The 1st is the result of expression1. If it's false then the 2nd operand does not evaluated at all. Of course, it does not bear a relation to your program logic. But formally it's a valid C++ expression statement...

I think you must get your textbook now and learn the very basic and simplest C++ syntax rules before typing help requests. I have never seen so surprising treatment of C++ language. Thank you, it's …

ArkM 1,090 Postaholic
int main()
{
    vector<int>  positions;
    list<char> letters;
    ifstream file("phrases.txt");
    string line;
    list<char>::iterator c;
    size_t i;

    while (getline(file,line)) {
        positions.clear();
        letters.clear();
        for (i = 0; i < line.length(); ++i)
            if (isalpha(line[i])) {
                letters.push_back(line[i]);
                positions.push_back(i);
            }
        letters.sort();
        for (i = 0, c = letters.begin();
            c != letters.end();
            ++c, ++i)
            line[positions[i]] = *c;
        cout << line << '\n';
    }
    cout.flush();

    return 0;
}

Homework: what STL headers needed to compile this improvisation?..

ArkM 1,090 Postaholic

What's a gibberish text after the last if! What a language are you using? It's not C++.
Moreover, it's not C# or Basic or.
Next time copy/paste someone else's code more accurately...

ArkM 1,090 Postaholic

At first define position specifications. For example, what's a position for inexistent item value? What's a position of the 1st node - and so on...

ArkM 1,090 Postaholic

Fortunately, it's so simple: ;)

cin.ignore('\n'); // skip 10 chars: '\n' == 10

The 1st ignore() member function argument: The number of elements to skip from the current read position. That's why you have "or the engine" wreck only.
Change to

cin.ignore(1,'\n');

or study the Narue's Novel About cin Flushing (see Ancient Dragon's post)...

ArkM 1,090 Postaholic

Yes, it is, but it's not a reference, it's a pointer to the 1st element of a vector contents (until you invoke any op changed vector's size or capacity).
The C++ Standard guarantees that std::vector contents occupies contiguous and properly aligned memory area.

ArkM 1,090 Postaholic

Yet another tip: you can get "mirrored" char with only one and a very simple expression without any explicit numbers...

ArkM 1,090 Postaholic
ArkM 1,090 Postaholic
const int N = 6;
    
    int n1 = 1, n2 = 0;
    int i, k, n;

    for (k = 0; k < N; ++k) {
        n = n1 + n2;
        for (i = 1; i <= n; ++i)
            printf(" %d",i);
        putchar(',');
        n1 = n2;
        n2 = n;
    }
    putchar('\n');
ArkM 1,090 Postaholic

It's suprising that you "have spent a long time trying to find library or useful class to help me perform matrix inversion". I have found then download some tested and ready-to-use freeware libraries in C++ with matrix classes and inverse operation for 10 minutes...

Regrettably at the moment I have no time to post all useful links gotten after my Google search (and more deeper surfing after that). May be you can post your test matricies examples (where your home-made product failed). Later I will try to install and test some of these libraries...

ArkM 1,090 Postaholic

Of course, "batch" is not a keyword. "Array" and "pointer" are not keywords too.
But we all know what is it an array and what is it a pointer in C++, but it seems only the author knows what is it mysterious "batch" in C++.
It's funny...

ArkM 1,090 Postaholic

OK: "array and pointers are not allowed to be used". What is it "batch"? I don't know such type (I hope, it's not an array ;)) in C++...

ArkM 1,090 Postaholic

Don't forget: std::cin is not alias for a keyboard input. It's an abstract char input stream. You can attach it to a file, for example. Moreover, std::cin is not defined for windowed applications. You describe possible keyboard input errors. But std::cin does not bear a relation to online user behaviour.

ArkM 1,090 Postaholic

Of course, you may ask the user to input size or what else. The problem is what to do with the answer.
Better explain your problem, present source code snippets...

ArkM 1,090 Postaholic

That's the fateful (and typical) mistake in the average value calculations:

double average;
  int sum = 0;
  ...
  average = (sum / 5); // *** integer division!

You try to assign the result of integer division to double value. You want to get exact average value. But 7/5 == 1, 9/5 == 1, 12/5 == 2 and so on. You lost a fractional part of calculated value. It does not matter what's a type of a target.

If you want to get an exact (more precisely, double type) result, make float division, for example:

average = sum / 5.0; // Type of 5.0 constant is double
Sky Diploma commented: LEARNED something New ;) Thx +1
ArkM 1,090 Postaholic

Look at the trailed backslash:

// Test constructors\
  Complex c1, c2(6.35), c3(-5.5, 3.0);

It's a continuation-line character in C and C++. The next line now is a part of a single-line comment, so you don't declare c1, c2 and c2 variables!

The 2nd error is hidden (for the present):

#ifndef Complex_H
#define Complex_h

The C++ names are case sensitive ones. So your header file protection does not work: you define the different macros name.

That's all for now...

ArkM 1,090 Postaholic

1. If you are using stdafx.h (in MS VC++), place all system includes in stdafx.h, not in your source modules.
2. Why #include "stdio.h" ? Must be #include <stdio.h> directive in stdafx.h.

ArkM 1,090 Postaholic
ArkM 1,090 Postaholic

Your Windows installation does not know where is the g++ executable. See
https://users.cs.jmu.edu/bernstdh/web/common/help/cpp_mingw-faq.php

ArkM 1,090 Postaholic

About this thread starting question: look at my posts in solved threads (two month ago):
http://www.daniweb.com/forums/thread136351.html
http://www.daniweb.com/forums/thread137814.html

ArkM 1,090 Postaholic

It seems a loop control is your weak point now...
Look at the finalgrade function again:

...
    for (int i = 0;i<4; i++)   {
        totalpoints = (testscores[i] + labscores[i] + projectscores[i] + finalexamscores[i]);  
   ...

So i = 0, 1, 2, 3. But your arrays have index range 0..2 (for the 1st, 2nd and 3rd) and 0 (only one element) for the 4th! You get unexistent array element values for i = 1, 2 and 3. I don't know why you assign so strange values for your arrays, but your finalgrade function does not know it too. It produces wrong results for totalpoints.

Now about totalpoints to char translation. No the last else clause in if cascade so if your have totalpoints value out of range the function does not return any valid value. It's your case: you get wrong totalpoints value then return garbage char value. If the function returns 0 (for example), output statement prints nothing (0 is non-printable char).

Terminate if cascade with else return '\?'; to explicitly designate wrong situation.

ArkM 1,090 Postaholic

It's funny that you program prints anything: the only purpose of this code now is the program stack corruption. The 1st index in C and C++ arrays is 0 (not 1!). All for loops in your input routines are wrong.
See also finalgrade function: not all control paths return a value.
Make obvious corrections then try again...

ArkM 1,090 Postaholic

10 hours ago Sci@phy told you about this error.
You wrote:

int power (int n); // function prototype//
int main(void)
{ ...
    printf("\n %.4f to the power of % d is %.4f",a,n,power(a,n)); 
...
} /* the main does not know about this fucntion: no its prototype */
float  power(float a, int n)
{...

At the 1st line you tell (to compiler) that power function has one parameter of int type. Of course, no such function in your code. You tell lies. In printf you call power function with two arguments. The compiler knows that power has one argument only, it sends obvious message to you:
'power' : function does not take 2 arguments.
If you want to call your power function, write correct prototype instead of senseless int power(int) .

It seems you don't understand all ours posts to you...

ArkM 1,090 Postaholic

1. Better follow standard pow pattern: use double type for argument and returned value.
2. Some useful method: extract recursive part to reduce a number of operators in recursion:

static double powrec(double x, int n) {
    return n? x * powrec(x,n-1): 1.0;
}
double powint(double x, int n) {
    if (x == 0.0) /* if n < 0? */
        return 0.0;
    else if (n == 0)
        return 1.0;
    else if (n < 0)
        return powrec(1.0/x,-n);
    return x * powrec(x,n-1);
}

The only test in a recursion instead of 3...

ArkM 1,090 Postaholic

The sprintf does not implement itoa functionality (radix in 2..36 range).
Fortunately, it's so simple to get itoa portable solution:

/* The Itoa code is in the puiblic domain */
char* Itoa(int value, char* str, int radix) {
    static char dig[] =
        "0123456789"
        "abcdefghijklmnopqrstuvwxyz";
    int n = 0, neg = 0;
    unsigned int v;
    char* p, *q;
    char c;

    if (radix == 10 && value < 0) {
        value = -value;
        neg = 1;
    }
    v = value;
    do {
        str[n++] = dig[v%radix];
        v /= radix;
    } while (v);
    if (neg)
        str[n++] = '-';
    str[n] = '\0';
    for (p = str, q = p + n/2; p != q; ++p, --q)
        c = *p, *p = *q, *q = c;
    return str;
}
ArkM 1,090 Postaholic

>you can actually calculate a more accurate solution without using a power function

Probably you can do that but not with this series. You must calculate over 250 terms to achieve log(result) == 156 (slower than pow with factor ~25) but pow approximation of e^156 is better than sum of 250 terms. You need over 1000 terms to get 10 right digits of e^156 but the pow gets 12-13 right digits...

In real world nobody (except students and teachers;)) compute standard functions with series: it's too slow and low precision approach...

ArkM 1,090 Postaholic

Thank you all participants for a very interesting discussion in the thread.
Some additions:
Let's remember what is a copy constructor in C++. Copy constructors are (C++ Std, 12.8):

A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments
...
Note: all forms of copy constructor may be declared for a class.

A compiler-generated (default) copy constructor always has const X& parameter. Some careful compilers print warnings if you have more than one copy constructor declared for a class (VC++ 9, for example, does it). I think, it's a very helpful warning in most of cases.

If a class has a copy constructor with X& parameter, this constructor works for non-const initializer (see the 1st post of the thread). It does not matter what "constantness" of initialized object (see an example with Func parameter binding).

So it's possible to modify a non-const only ARGUMENT object (initializer) via X& copy constructor of another object. Sometimes it's useful feature but as usually is an example of bad practice...

At the same time let's repeate that constantness of ordinar (free, not-member) functions parameters is not a part of function signatures. So it's an error to define two functions:

void F(X x) { ... }
void F(const X x) { ... }

All static member …

ArkM 1,090 Postaholic

Why you include readcharacter.cpp in the "other file"? It seems you don't understand the principle of a splitting a program to separate modules. Now you have ReadCharacter function body in both modules. Of course, the linker (it's a part of your programming system: linker builds exe from separately compiled modules) issues this diagnostic message. The linker does not know about line numbers: it works with compiled (object) modules.

There are many others suspicious code fragments in your code. For example:

Character InheritCharacter;//Class Declaration

Do you know that it's NOT a class declaration in C++? A class declaration is a construct started with:

class Character ... { ...

Or

... j<sizeof(Danger)/sizeof(std::string); ...

I hope you know that sizeof(std::string) is not a length of a string contents. Congratulation! You have wrote a very cryptic code: where is Danger declaration? Probably, it's a global string array declared in .h file. But if it's a pointer to dynamically allocated string array, you will have some troubles.
Now CompareThisCharm and Magic are strings.

CompMagic=Magic.compare(CompareThisCharm);
if(CompMagic == 0)

What for so mannered code? Keep it simpler:

if (Magic == CompareThisCharm)

You have a lots of global variables in numerous header files. As a result of this bad design solution it's absolutely unclear what every module must do, what's types of variables. Avoid this obviously bad programming style now...

Apropos, why you declare string parameters but not using references to string (string& type). You have unwarranty expensive codes - …

ArkM 1,090 Postaholic

Alas, you write itoa result to nowhere. Just before itoa call YOU say: my hexData pointer points to NOWHERE (NULL is this NOWHERE).
You must pass a real memory pointer to itoa. Declare a char array or allocate memory chunk by new operator.
Or (better) reread your C or C++ textbook...

ArkM 1,090 Postaholic

To all appearances you are trying to reinvent std::valarray class ;).
Look at <valarray> header of your C++ installation. For example, in MS VC++ 9 you can see:

template<class _Ty>
class valarray
{ // store array with various indexing options
...
    valarray<_Ty> operator+() const
    {    // return +valarray
        _VALOP(_Ty, size(), +_Myptr[_Idx]);
    }
...
};
...
template<class _Ty> inline
valarray<_Ty> operator+(const valarray<_Ty>& _Left,
	const _Ty& _Right)
{   // return valarray + scalar
    _VALOP(_Ty, _Left.size(), _Left[_Idx] + _Right);
}

template<class _Ty> inline
valarray<_Ty> operator+(const _Ty& _Left,
	const valarray<_Ty>& _Right)
{   // return scalar + valarray
    _VALOP(_Ty, _Right.size(), _Left + _Right[_Idx]);
}
...

So Sci@phy got you a good advice.

Yet another remark: object+int or int+object do not bear a relation to associativity. Left/right associativity is:

x ? y ? z evaluated as ((x ? y) ? z) // Left associative op ?
x ? y ? z evaluated as (x ? (y ? z)) // Right associative op ?

See http://en.wikipedia.org/wiki/Associative

ArkM 1,090 Postaholic

Yet another wrong code fragment:

#define ROWS 2
#define COLUMNS 2
...
    for (i=0; i<3; i++) { // *** < 2 or better < ROWS
        for(j=0; i<3; i++) // *** j++ !!!; 
            // *** < 2 or better < COLUMNS
            cout << Screen_Array[i][j];
    }
ArkM 1,090 Postaholic

It's not only the way of solving the compile-time warning problem, it's the way of solving right (run-time) calculations problem.
If we have unsigned long i and unsigned short x = 0xFFFFu and unsigned short y = 0xFFFFu then i < x * y computations are:
1. Do integral promotions for both multiplication operands (unsigned short to int)
2. Multiply int to int (int result 0xFFFE0001, integer overflow ignored in VC++)
3. Do int to long promotion of 0xFFFE0001 (do nothing in 32-bit VC++) then long to unsigned long conversion (the same 0xFFFE0001u but positive now; do nothing in 32-bit VC++).
4. Compare i with positive 0xFFFE0001.
Strictly speaking we have an unportable code: some C++ implementation may diagnose integer overflow in step #2! So explicit cast of x and y is the way to do this code portable.

ArkM 1,090 Postaholic

It's so simple to solve your problem (if you can't follow skatamatic's advice):

for ( unsigned long i = 0; i < (unsigned long)x * (unsigned long)y ; i++ )
ArkM 1,090 Postaholic

I think it's a very interesting question. From the C++ Standard (4.5, 1):

An rvalue of type char, signed char, unsigned char, short int, or unsigned short int can be converted to an rvalue of type int if int can represent all the values of the source type; otherwise, the source rvalue can be converted to an rvalue of type unsigned int.

No doubts that VC++ int type can represent all the values of unsigned short. So x * y result was promoted to int (not to unsigned int). That's why this diagnostic message was generated (unsigned long < int and so on)...

Salem commented: Nice. I thought it was something like that, but couldn't find "chapter and verse". +21
ArkM 1,090 Postaholic

You try to get tax_rate with wrong format specifier (%d used only for int values but your tax_rate is float).
Must be:

scanf("%f", &tax_rate);

Better use double type for all your numbers. Don't forget that input format specifier for double is %lf, not %f.

ArkM 1,090 Postaholic

You are looking for a deep copy silver bullet but your compiler does not know the semantics of this operation for your classes. YOU know the semantics. That's why user-defined copy constructor and overloaded assignment operator were invented in C++.

It's a matter of the right object model design. For every new class think about its possible copiable property in good time. Your compiler is not able to think in place of you.

Think about boost::shared_ptr using, for example...

ArkM 1,090 Postaholic

In addition to invisal's post:
Don't compute p raised to the power dig with floating point arithmetic pow function. It's too expensive. Better write your own simple integer pow function, for example:

int ipow(int k, int n)
{
    int kn = k;
    while (n-->1)
        kn *= k;
    return kn;
}

It's far from the fastest method but it's better than pow(). Think about using table (array) of powers (there are only ten digits for base 10 ;)).

Think about better condition for the last loop. No need to continue calculations if the partial sum of powers is greater than the number (it's not one of Armstrong numbers).

Look at for loops in C textbook: your while loops are for loops simulations.

Use "%d\n", not "\n%d" format to print the next number.

ArkM 1,090 Postaholic

From http://homepages.cwi.nl/~dik/english/mathematics/armstrong.html:

An Armstrong number is an n-digit base b number such that the sum of its (base b) digits raised to the power n is the number itself.

a = a^1 { 1, 2, 3, 4, 5, 6, 7, 8, 9 }
ab = a^2 + b^1 {}
abc = a^3 + b^3 + c^3 { 153, 370, 371, 407 }
abcd = a^4 + b^4 + c^4 + d^4 { 1634, 8208, 9474 }
and so on...

ArkM 1,090 Postaholic

All C compilers create all arrays as 1D arrays: the C language defines a strict mapping of multi-dimentional array to contiguous 1D array...

ArkM 1,090 Postaholic

Ohh, read my snippet again.
Look at cmd.c_str()! It's std::string to const char* conversion!

I know you are a beginner to C++ (but I think true C++ beginners do not starting from RegOpenKey stuff). They are starting from the C++ language basics.

Well, continue your C++ studies with copy/paste training:

#include <iostream>
#include <windows.h>
#include <string>

using namespace std;

int main()
{
    string unrealpath;
    HKEY hKey = 0;
    char unreal[255] = {0};
    DWORD dwType = 0;
    DWORD dwUnrealSize = sizeof(unreal);
    const char* subkey = "Software\\Unreal Technology\\Installed Apps\\Unreal Gold";

    if( RegOpenKey(HKEY_LOCAL_MACHINE,subkey,&hKey) == ERROR_SUCCESS)
    {
        dwType = REG_SZ;
        if( RegQueryValueEx(hKey,"Folder",0, &dwType, (BYTE*)unreal, &dwUnrealSize) == ERROR_SUCCESS)
        {
            unrealpath = "\""; // Starting quote
            unrealpath += unreal; // Append dir path
            unrealpath += "\\System\\Unreal.exe\""; // Append the last part with quote
            // Can you insert debugging print of unrealpath here?..
            system(unrealpath.c_str());
        }
    }
}
ArkM 1,090 Postaholic

Modify the same approach:

std::string cmd;
...// get dir name into buf then
cmd = "\"";
cmd += buf;
cmd += "System\\Unreal.exe\"";
// Now you have quoted exe path with
// "F:\Tolvuleikir\Full\FPS\Unreal Anthology\UnrealGold\System\Unreal.exe"
// Append cmd parameter(s):
cmd += " -800";
system(cmd.c_str()); // Start the application

It works fine with VC++ RTL system() call.

Also you may use non-standard spawn family functions from <process.h>.

ArkM 1,090 Postaholic

1. Add #include <string>
2. Add

string path;
...// get dir name into buf then
path = buf;
path += "System\\Unreal.exe";
// Now you have string path with
// "F:\Tolvuleikir\Full\FPS\Unreal Anthology\UnrealGold\System\Unreal.exe"
system(path.c_str()); // Start the application

3. Don't muddle double backslashes in source text literals with "friendly executable format".
4. I don't understand why you insert quotes (after Anthology, for example) in the result string example:

F:\\Tolvuleikir\\Full\\FPS\"\\Unreal Anthology\"\\UnrealGold\\System\\Unreal.exe" so I would then be able to do: system("Unreal") and it would know that I wanted to execute the path contained by the int "Unreal".

And you? Do you understand why?..

ArkM 1,090 Postaholic

Don't waste time on these vector based solution debugging troubles.

typedef std::map<std::string,int> Dictionary;
typedef Dictionary::iterator Diter;
typedef Dictionary::const_iterator Citer;
typedef std::pair<std::string,int> V;

// I don't like to inherit from STL classes...
struct Dict
{
    Dict& ins(const std::string& word);
    Dict& ins(const char* pword) 
    {
        if (pword)
            ins(std::string(pword));
        return *this;
    }
    Dictionary dict;
};
// Increment counter if the word found.
Dict& Dict::ins(const std::string& word)
{
    Diter d = dict.find(word);
    if (d != dict.end())
        (*d).second++;
    else // new word
        dict.insert(V(word,1));
    return *this;
}

int main()
{
    Dict d;
    d.ins("vector").ins("all").ins("problems");
    d.ins("avoided").ins("no").ins("vector");
    for (Citer p = d.dict.begin(); p != d.dict.end(); ++p)
        std::cout << (*p).second << '\t' << (*p).first << '\n';
    std::cout.flush();
    // If you want vector of word+counter, here it is:
    std::vector<V> v(d.dict.begin(),d.dict.end());
    std::cout << '=' << v.size() << std::endl;
    return 0;
}
/* Output:
1       all
1       avoided
1       no
1       problems
2       vector
=5
*/
Alex Edwards commented: Excellent usage of the STL components! +4