ArkM 1,090 Postaholic

1. About C4716: didn't you know that double F_Ite() function must return double type value? And where is return anything-of-double_type in the function body? It's your code, you have wrote double F_Ite() ...
2. Use code tag with the language specifier (see this forum announcements):
[code=cplusplus] source

[/code]
It's impossible to cope with this unformatted nightmare!
3. There are two common ways to "return" several values:
3.1 Declare several function parameters (pointers or references to targets).
3.2 Declare a proper struct or class compound type then fill the object of this type and return it as a function value.

tux4life commented: The actual thread solver :) +9
ArkM 1,090 Postaholic

Don't worry, it's a small code ;)
Try to split functions into separate groups by themes (as usually, it's possible to do). Place every group in a separate cpp file (don't forget to add it to the project). Move all functions prototypes into .h file and include it in every cpp file (in main file too).
Done.

ArkM 1,090 Postaholic

Insert std::cin.ignore(1000,'\n'); after std::cin >> diameter;

ArkM 1,090 Postaholic

>...why is this i cannot see anything wrong with my code...
Oh, this harmful Daniweb engine! I see 'area' in the OP snippet but area in the post #3 code ;)
By the way, change char area; to float area; ...

ArkM 1,090 Postaholic

Fill a glass with water (or what else) then drink, not vice versa ;)

Calculate a circle area AFTER its diameter request.
Output the area variable, not a wrong character literal 'area'...

ArkM 1,090 Postaholic

>I'm not quite sure what exactly you mean. I'm really new to C++. Can you explain a bit more clearly?
OK, let's come back to the class Path design. The class has a member function without parameters: scPrint. It prints (in a very strange manner) a message:

void Path::scPrint() const 
{
    cout << "*** Starting in " + scArg + " ***" << endl;
    cout << "Print out of all flights starting in particular city" << endl;
}
// That's right:
    cout << "*** Starting in " << scArg << " ***\n";
         << "Print out of all flights starting in particular city" 
         << endl;
}

Evidently a class object has a default starting point. In other words, a starting point name is an attribute of Path object. If so, we must define this attribute in Path constructor or later but before scPrint using - for example:

class Path
{
public:
    Path():scArg("Unknown") {}
    Path(const string& sc): scArg(sc) {}
    ...
    void setOrg(const string& sc) { scArg = sc; }
    string& getOrg() const { return scArg; }
...
private:
    string scArg;
    ...
};

Now you can create Path objects in the main:

Path* path = new Path(argv[3]);
// or
Path path;
...
if (string(argv[2]) == "SC") {
    path.setOrg(argv[3]);
    path.scPrint();
}

What's a problem?
Did you really not know what's a class constructor? ;)

ArkM 1,090 Postaholic

Well, your program crashed. It looks like a mere assertion, not a question.
Read This Before Posting: http://www.daniweb.com/forums/thread78223.html.
Never send exe files in attachments!

ArkM 1,090 Postaholic

What a wonderful teleportation of argv[3] to every class Path object do you want? If you have a "default" starting point of the Path object (probably it's the scArg member), provide this class for a correspondent constructor or default starting point setting member function - that's all.

ArkM 1,090 Postaholic

Okay.

Thanks all. I understand why I was getting my problem now and also was able to fix some more problems in my code.

If so, mark this thread as solved ;)

ArkM 1,090 Postaholic

Better use std::string class:

#include <iostream>
#include <string>
using namespace std;
...
string day;
...
getline(cin,day);
if (day == "Mo") ...

To compare C-style strings use strcmp function from <cstring> header:

if (strcmp(day,"Mo") == 0) ...

Now in day == "Mo" you compare pointers (not contents). Of course, you will never get true...

ArkM 1,090 Postaholic

1. Well, reserve size (if no need in some postprocessing)
2. Tastes differs; for example, I prefer to return bool in such cases. I think, returned size if more useful than 0. Moreover, zero on success is not a natural code, look at:

if (!FileToString(...)) { // Haha, if NOT means SUCCESS
ArkM 1,090 Postaholic

The wittingly wrong statement in OP code is delete buffer; - must be delete[]buffer; . Yet another defect: insufficient error check-up.

long GetFileSize(ifstream &file)
{
    static const streamoff badPos(-1);
    if (!file)  // test added
        return -1;
    streamoff temp = file.tellg();
    if (temp != badPos && file.seekg(0L, ios::end)) {
        streamoff end = file.tellg();
        if (end != badPos && file.seekg(temp, ios::beg))
            return static_cast<long>(end);
    }
    return -2;
}

/// Load the file to fileS string, return filesize. 
/// Non-positive returned if failed
long FileToString(const string &file_path, string &fileS)
{
	ifstream input(file_path.c_str(), ios::binary);
    if (!input) { // simple and clear stream state test
        fileS.clear(); // no contents
        return -1;
    }
	long size = GetFileSize(input);
    if (size <= 0) { // filesize test added.
        fileS.clear();
        return -2;
    }
	char* buffer = new char[size];
    if (input.read(buffer, size)) {
        fileS.reserve(size+size/10); // add reserve
	    fileS.assign(buffer, size);
    } else {
        size = -3;
    }
	delete [] buffer; // [] inserted!
	//input.close(); // no need: let destructor works
	return size;
}

About wrong filelist parsing (adatapost's tip):

If you want a portable code, never use FileToString to load line-oriented filelist file. It's the case where binary (low-level) stream/string processing is an absolutely irrelevan method. The old good std::getline is the best and the portable tool to "tokenize" a simple text file!

By the way, never add non-inline function definitions in .h files! Have you ever heard about separate compilation? Only function prototypes are placed in .h files.

CppFTW commented: Thanks! +1
ArkM 1,090 Postaholic

Your constructor variant with assignments has the same effect as mine. However as usually assignments in constructors (or even anywhere) are less effective than initialization with ctor-initializers (and are less clear). Yes, formally in your case the compiler initializes an empty string member then creates a temporary string object (for Suite(const char*) constructor) and performs assignment after that. Besides that, ctor-initializer semantically (and pragmatically) directs a (good) compiler to the best optimization of constructor codes.

That's why ctor-initiaslizer-lists are better than assignments. Whenever you have a choice, select ctor-initializer. Don't forget: a constructor is intended for an object initialization.

ArkM 1,090 Postaholic

In addition:
Change lines 40-45 in my code above to

/// more syntax sugar for lazies
const Suite 
    &Hearts = Suite::Hearts,
    &Clubs  = Suite::Clubs,
    &Diamonds = Suite::Diamonds,
    &Spades = Suite::Spades
    ;

Probably it's more effective...
I hope you understand that it's an optional code...

ArkM 1,090 Postaholic

This part is so called ctor-initializer-list. In C++ it's a preferred way to initialize class members and the only method to pass constructor arguments to base class(es) constructors (the last feature is not used here). Alas, it's impossible to initialize non-integral types static data members in ctor-initializer-list. That's why we do it separately in lines 32-37.

So

Suite(const Suite& suit):value(suit.value) {}

is the class Suite copy constructor: it creates a Suite object from another object of the same type.

The point is that we must define all needed constructors (default constructor - line #5, copy constructor - line #6) if a class has user-defined constructor (see line #23).

Take into account that I don't want to allow users to construct arbitrary Suite objects (like Suite card("Cheat") ). That's why the constructor defined in line #23 is protected. Now we can initialize four static Suite objects (lines 32-37) and construct all others via the copy constructor.

To allow Suite object arrays we need Suite default constructor (a constructor without parameters).

Oh, as usually {} means copy constructor body (a constructor is a member function). It's inline constructor - no need to call any real functions to construct a Suite object with this constructor.

More questions?..
;)

ArkM 1,090 Postaholic

Are you sure that your method is not efficient?
Why?..
What's your efficiency criterion?

Salem commented: Getting someone else to do it with the minimal amount of explanation ;) +34
ArkM 1,090 Postaholic

Of course, all possible in C++ ;)
That's an improvisation:

/// suite.h (class Suite definition)
class Suite
{
public:
    Suite() {}
    Suite(const Suite& suit):value(suit.value) {}
    static const Suite 
        Hearts,
        Clubs,
        Diamonds,
        Spades;
    /// that's all, add some methods...
    const string& str() const { return value; }
    /// add some syntax sugar:
    operator bool() const { return !value.empty(); }
    bool operator ==(const Suite& suit) {
        return value == suit.str();
    }
    bool operator !=(const Suite& suit) {
        return value != suit.str();
    }
protected:  // there are four colours only
    Suite(const char* suit):value(suit) {}
private:
    string value;
};
inline // add stream output support
ostream& operator <<(ostream& os, const Suite& suit) {
    return os << suit.str();
}
/// suite.cpp (class Suite implementation)
const Suite 
    Suite::Hearts("Hearts"),
    Suite::Clubs ("Clubs"),
    Suite::Diamonds("Diamonds"),
    Suite::Spades("Spades")
    ;
/// test.cpp:
/// more syntax sugar for lazies
const Suite& 
    Hearts = Suite::Hearts,
    Clubs  = Suite::Clubs,
    Diamonds = Suite::Diamonds,
    Spades = Suite::Spades
    ;

int main()
{
    Suite suit;
    suit = Spades;
    Suite card(Clubs);
    if (card && suit == Spades)
        cout << suit << '\t' << card << endl;
    return 0;
}
tux4life commented: ArkM, always making the threads fun to read :P +9
ArkM 1,090 Postaholic

>...if you want to be a pedant...
To make distinctions between static, automatic and dynamic attributes - is it too pedantic for you?
;)

ArkM 1,090 Postaholic

In C you can assign void* type pointer value to the pointer of any type without casting. So simply declare a proper type pointer and set it to the buffer:

char* pchar = buf_ptr;
char* ptr = pchar + 20;
...
...pchar[20] the same as *ptr...

It's impossible to subscript void* pointer because sizeof(void) is not defined (type void has an empty set of values).

ArkM 1,090 Postaholic

>short answer: static arrays are allocated when the function is called...
Short remark: static arrays are allocated before the first call of the function. However no static arrays in OP snippet. Please, be more thoroughs in terms using.

ArkM 1,090 Postaholic

>What evil being designed such a thing?!
Probably, it was the hardware architect's acute condition ;)
Many years ago...

ArkM 1,090 Postaholic

>I want the minimal pointer because it is the left most node for my tree.
The leftmost node in the tree is not the same as the minimal pointer!
Moreover, a pointer value does not bear a relation to the node position in the tree.
Make a loop from the root via child[0] pointers until you have found a leaf - that's a node with an empty child vector. That's the leftmost node of the tree (probably ;))...

ArkM 1,090 Postaholic

>not many people will ever touch something like a 4-bit machine or any other sort of setup.
None the less there were supercomputers with 6-bits and 9-bits (or may be 12) bytes ;)
Moreover, I have seen a real computer with various byte widths (every 6-th byte was shorter than others)... ;)

ArkM 1,090 Postaholic

>I dont want the data inside i want the pointer
Which pointer do you want (and why) - that's a question ;)

If you want the minimal pointer value ( why?! ) - you have it. What's a problem? Well, there are two defects in your function:
1. if child (or childrent) size == 0 then root->child[0] raises memory access exception.
2. Start the loop from i = 1.

ArkM 1,090 Postaholic

Probably you want a pointer which points to the minimal data value. In actual fact it's (as usually) senseless operation to compare pointer values. Moreover, the result of pointers comparison is well-defined only if two pointers points to the same array.

If so, compare data values, not pointers. Save pointer value which refers to the minimal data value. Return this pointer - that's all.

Can you post node type definition? It's hard to say more without this info...

Next time use code tag with the language specifier:
[code=cplusplus] source text

[/code]

ArkM 1,090 Postaholic

>More random calls will tend to dilate the variance.
The variance of... what? We didn't estimate random sequence parameters in that case so the variance (or other moments) does not bear a relation to the sequence of 20 random numbers.

ArkM 1,090 Postaholic

A day ago csurfer's algorithm solved the problem. That's "pipelined" version:

int i, j = rand()%20;
    for (i = 0; i < 20; i++)
        array[i] = (i != j)*(rand()%9 + 1);

In addition: it's impossible to add another level of randomness by random shuffles or other tricks while we are using the same (extremely bad ;)) rand() generator.

ArkM 1,090 Postaholic

That's it:

5.2.4.1 Translation limits
1 The implementation shall be able to translate and execute at least one program that contains at least one instance of every one of the following limits:
...
- 12 pointer, array, and function declarators (in any combinations) modifying an arithmetic, structure, union, or incomplete type in a declaration
...
Implementations should avoid imposing fixed translation limits whenever possible.

(256 in C++)

ArkM 1,090 Postaholic

Try to append LL suffix to long long constants.

Salem commented: ArkM blazes in with both barreLLs for the win ;) +33
tux4life commented: Sometimes it's so simple that you even don't think about it :P +8
ArkM 1,090 Postaholic

>What do you mean? All memmove does is move memory. So even if you want to use your own class object, it should still work.
It's so simple. Suppose the object has a member which is a head of double linked list (why not?). Now move it by memmove and think about the back pointer of the 1st node and the next pointer of the last one (both refer to the list head). That's why we overload assignment operator for complex classes. I'm sure that you can invent other (simple) examples of such classes.

Moral of a story: use memmove for POD variables only, never use it for class objects.

ArkM 1,090 Postaholic

William, we don't know base element type. If it's a class object (see OP), memmove can't move elements correctly! Moreover, remove class object means call destructor...

ArkM 1,090 Postaholic

Of course, the original post is extremely ill-formed.
However at least one defect arrests attention: sort_names function is wrong. Sorting loop index is out of range: names[j+1] refers to inexisting string element when j == size-1.

To OP: don't try to start this code as is: there are too many other defects in this program now. Debug it step by step. For example, take sort_name function, write a simple test case and try to debug it then take another function (Menu, read_... etc). Don't force to play a team of cripples.

ArkM 1,090 Postaholic

Too many problems on a single (and simple) program case is a symptom of bad design solution.

Evidently in that case you need different data structure. You want dynamically defined data structure size - but an array size in C++ is a compile-time defined (constant) expression. You want to remove selected elements - but an array never changes its size after allocation.

Better think about STL vector container.

std::vector<Object> v(rand()%3+1);
cout << v.size() << " elements\n";
...
v.erase(v.end()-1);  // remove last
...
v.erase(v.begin()+i);// remove i-th
...
Object obj;
v.push_back(obj); // append new obj
ArkM 1,090 Postaholic

Why strncat? Make a single (expected) string by a single snprintf call. What's a problem?

ArkM 1,090 Postaholic

Initialization of class members (except static integral types):

class Ob // avoid all small letters names
{
public: // declare public then protected then private
  Ob():name("Name") {} // member initializators list
  ...
private:
  std::string name; // initialize in constructor(s)!
};
ArkM 1,090 Postaholic

void openfile(char *,FILE**)
what does double stars indicates

The second argument type is a pointer to a pointer to FILE type.
Didn't you understand what's a pointer?
Evidently this function returns FILE* pointer via this argument. What's a strange perversion...

ArkM 1,090 Postaholic

absread:
What's it: ancient TC non-standard function to read a sector from the HD in native DOS environment.
Usage: forget as soon as possible.

ArkM 1,090 Postaholic

>the program encrypts the text at a rate of about 5000 characters per second on a 500mhz Intel Pentium 3 running windows xp pro.
It looks like an extremely low speed. I think that's a lower bound of a "good" speed (for more complex than DES chiphers): ~5-10 Mbytes/second. Try to optimize your code. I'm sure that's possible to do...

ArkM 1,090 Postaholic

Excuse me, siddhant3s: I have not seen your post above! :(
No need in my post now.

ArkM 1,090 Postaholic

According to the C and C++ standards

int array[....];

array[-2] - wrong expression, because array-2 points to inexisting array element (the only exception: pointer to the 1st element after array end). Therefore we can't dereference it in *(array-2) expression (that's array[-2] by definition). Moreover, array-2 value is undefined in that case.

In actual fact binary (with two arguments) built-in subscript operator[] is defined for pointer-integral arguments pair but not for array-integral pair only. That's why p[-2] may be legal subscript if (and only if) p points to an array element with index greater than 1, for example:

int  array[10];
int* p = &array[2];
p[-2] = 0; // same as array[0]

Of course, it's not the same as negative array index.

ArkM 1,090 Postaholic

It's so interesting: what's your context? There is a wonderful context: Internet. For example:
http://www.cprogramming.com/tutorial/stl/stlmap.html
and lots of other links to std::map tutorials...
Have you ever heard search Google phrase?
;)

ArkM 1,090 Postaholic

It's so easy: use std::map<std::string,planet>.

ArkM 1,090 Postaholic

The funny part is: all this doesn't happens in the line previous to this. That is perhaps because of your compiler's smartness, it doesn't promote -1 to int but demotes x to a int.

1. Probably you mean doesn't promote -1 to unsigned int...
2. All this happens in int a = (int)-1 * x . The funny part is: (int)-1 is the same as -1 because an integer literal already (and always) has int type. The compiler never takes into account left part type: it promotes -1 to unsigned int (max value) then multiply it to unsigned(10) (ignores integer overflow). After that the result is unsigned(4294967286) or int(-10) - the same bit pattern...

ArkM 1,090 Postaholic

Try to understand the standard compilation process logic.

Simplified translation process description:

1. Every .cpp file is processed separately (as if no other cpp files)

2. Preprocessor stage: process all # directives. Every active (see AD's post, #ifdef/#ifndef directives) #include directive in .cpp file is replaced by referred .h (or other) file or header (named in angle brackets) contents (recursively, until all includes are replaced)

3. This is a translation unit text. It's compiled.

Now consider your case. You have Points definition in structpoints.h file. You have #include "structpoints.h" in test.h file. You have #include "structpoints.h" and #include "test.h" directives in test.cpp. Now try to compile test.cpp - see points above:

1. Get test.cpp
2. Replace #include "structpoints.h" . It's Points definition. Replace #include "test.h" to its contents and recursively replace yet another #include "structpoints.h" ! That's yet another Points definition in this translation unit - you breaks "one definition" rule.

No magics...

Now try to understand AD's solution of the problem.

ArkM 1,090 Postaholic

More precisely: if the program attempts to modify an array corresponding to a string literal, the behavior is undefined.

ArkM 1,090 Postaholic

Place your struct type definition in .h file:

struct Points {
  int xCoordinate;
  int yCoordinate;
  int zCoordinate;
};
... global functions prototypes

Include this .h file in all modules (.cpp files) where Points type needed (in the main file too). Change array point declaration to

// main cpp
#include "h-file-name"
...
Points point[150];
...

That's all.
Think: now you have Points type definition in the main file only. Of course, it's unknow type in other files.

ArkM 1,090 Postaholic

Here it goes..... text file attached!

And where are data declarations?
;)
Please, Read This Before Posting: http://www.daniweb.com/forums/thread78223.html

ArkM 1,090 Postaholic

Where is the code?

ArkM 1,090 Postaholic

Well, let f(i) is i-th member without sign (it's not C).

f(i) = i/i! = i/(1*2*...*(i-1)*i) =
i/(i*(1*2...*(i-1)) = 1/(i-1)!
f(i+1) = 1/i! = 1/((i-1)!*i) = f(i)/i
i = 1, 2,... (0! = 1 by definition)

In other words, if we know i-th member of series then the next member is equal to this member / i (ignore sign).
if we know that i-th member is positive then the next member is negative and vice versa.
We know that 2-nd member is equal to -1.0 (negative). We know that the partial sum of the series is equal to 1.0 at this moment: f(1) == 1/1!...

Now we must define calculation loop condition. Obviously no sense to continue calculations when the next member of series is too small: double type precision is ~16 decimal digits. We want to stop calculations when f(i) < eps, where eps == 1e-16 (for example).

Yet another tip: no need in int variables at all!

double Series()
{
    const double eps = 1e-16;
    double sum = 1.0; /* sum(1) */
    double f, i;
    int neg = 1;/* the 2nd member < 0 */
    for (f = 1.0, i = 2.0; f > eps; f /= i, i += 1.0) {
        /* cout << i << '\t' << f << '\t'; */
        sum += (neg? -f: f);
        /* cout << setprecision(15) << sum << '\t' 
              << (sum?1/sum:0) << '\n'; */
        neg ^= 1;
    }
    /* cout << sum << endl; */ …
ArkM 1,090 Postaholic

See: you have fac > no for all no values because fac = n!. Therefore no/fac == 0 (integer division) and com=com+j is the same as com += 0...

1. Use double type for math calculations (not float).
2. Use floating-point division if you want to get floating-point result, for example:

com += (double)n/fac;

3. You will get (unsignalled) integer overflow in factorial calculation: 13! is greater than max integer value.

Better search DaniWeb for series: there are lots of threads on this topic. It's a bad approach to calculate factorial for every series member...