Banfa 597 Posting Pro Featured Poster

Your logic in your first code listing just will not work. For example for(int r = 0; r < numRows; r++) you use numRows as the loop limit, but numRows is what you are trying to calculate. What will be its value the first time the loop is entered? 0 seems most likely so then the loop never executes. The same applies to numCols.

for(int c = 0; c < numCols; c++)
		    {
			fin >> value;
			fout << value << "\t";
			if(!(getline(fin, endLine)))
			numCols++;
		    }

You do realise that getline will consume all the data left on the current line. That means that the second time round the loop you will have finished processing the current line and the first value you read on line 3 will be the first value on the next line.

Also yo do not do nearly enough error checking, line 3 could result in one or more of the stream status bits being set.

As far as input is concern a newline is just another white space character. You will get no particular indication that you have gone pasted one. However the newlines are important to you because the indicate the number of rows. I would suggest doing line reads from the file and then parsing the data on the line using a istringstream to get the values/number of values on the line.

Banfa 597 Posting Pro Featured Poster

atoi() returns 0 on error. strtol() is the same function but converts it to long int.

If the text length is greater than 1 and the output is 0, that would indicate an error. Unless someone really wanted to put 000 in there or something.

Using stringstream to cast to int will also fail with output of 0 if the characters are not digits. Admittedly, stringstream is the more C++ way to do it.

You have answered your own question atoi does not return 0 on error 0 is returned for a number of reasons so a 0 return does not equate to a definite error.

strtol is not the same function because it returns a pointer to where the conversion finished so you can easily tell if the conversion finished because it reached the end of the string, white space or an invalid character. Also strtol will handle bases other than 10 which atoi wont but that isn't really relevant here.

Using stringstream with fail with the failbit set if the input characters are not digits. You can not use the output value of convert to integer as a test for success because there are no invalid output values.

Banfa 597 Posting Pro Featured Poster

No I mean more like

string line;
int value;
istringstream iss;

getline(cin, line); // Get a ine of input from user
iss.str(line);      // Put it into a stringstream for processing
iss >> value;       // Get an integer value

// At this point you can check the status bits of iss for failure 
// to convert the integer and you can get what is left in the 
// stringstream and see if it contains any additional characters
Banfa 597 Posting Pro Featured Poster

atoi() is unlikely to help because it has no error output, you could use strtol() however neither of those are C++ they are part of the C standard library and C++ provides the same functionality through the use of stringstreams.

Banfa 597 Posting Pro Featured Poster

You have 2 C++ files, test.cc and classclock.cc

The problem you highlighted in post 1 is at the link stage and is because you have compiled and linked test.cc maybe like this

g++ test.cc

what you need to do is compile test.cc, compile classclock.cc and link the output of the 2 compilations together because test.cc is referencing functions defined in classclock.cc

You might be able to do it something like

g++ -Wall -pedantic test.cc classclock.cc

Banfa 597 Posting Pro Featured Poster

If they have input only integer data then all there should be is a string of digits.

  1. So get you get a line of input

  2. Extract an integer from it
  3. Verify the rest of the line is blank

If either step 2 fails or the rest of the line is not blank at step 3 then you have an input error.

You can use getline for step 1 and then a stringstream for steps 2 and 3.

Banfa 597 Posting Pro Featured Poster

I already told you that in my first post. As to validating the rest of the address there isn't much you can do.

You can check that only valid characters are used and that length restrictions are not exceeded. You can find some of the details required here

Banfa 597 Posting Pro Featured Poster

You are looking for the @ and printing the address as soon as you have found it.

What you need to do is count the number of @ in the string then once the loop has finished if and only if you have exactly 1 @ print the address.

It seems to me a common error of inexperienced programmers when using a loop to perform some test to try to put the if conditional for success inside the loop. However there are many times, such as this, when the actual result comes from running the entire loop because the result is not dependent on the value of a single entry in the array but rather on the state of the array as a whole.

You use the loop to calculate that entire state then test the state after the loop has finished executing.

Banfa 597 Posting Pro Featured Poster

Look I know that GNU gcc can produce dependencies and I know that some third party make engines can produce dependencies but as I said I do not believe Microsofts nmake can produce dependencies, in fact as a make engine it is somewhat feature poor.

You keep saying that you want automatic creation of dependencies but I answered that with my first post, nmake does not do that and I am not aware of any tool in the Microsoft tool chain that does except using their IDE which if you are using nmake you are clearly no doing.

Banfa 597 Posting Pro Featured Poster

You just need to add a line to your make file that looks something like

<CFileName>.c : <HeaderFile1>.h <HeaderFile2>.h <HeaderFileN>.h

For all your C files.

Banfa 597 Posting Pro Featured Poster

When you have sent the HTTP request the data returned to you will be some headers followed by the contents of your page.

It will all be text and for now you can probably treat it as ASCII encoded text although strictly speaking HTTP can use a wide variety of text encodings.

Every header will be on a separate line, there is a list of possible headers here and every response will contain at least one header.

Following the last header there is a blank line before the start of the content.

So to find your content, the simple string, just read what is sent to you discarding everything until you get a blank line and the keep the rest.

Banfa 597 Posting Pro Featured Poster

I didn't think nmake did automatic detection of dependencies which means you will have to edit your make file(s) and manual type in you dependencies.

Banfa 597 Posting Pro Featured Poster

It sounds to me like you are making a design mistake. You shouldn't be permanently storing iterators you should create them when you need them they are essentially a temporary thing.

There is a good reason for this, for several of the containers under certain operations iterators can become invalid. For instance any operation that changes the capacity of a vector can invalidate all iterators into it.

Assuming you cant do something like std::vector<std::vector<std::vector<C> > > aObjects Then I would be tempted to write B something like

class B{
public:
    typedef std::vector<C>::iterator iterator;
    typedef std::vector<C>::const_iterator const_iterator;

    iterator begin ()
    {
        return cObjects.begin();
    }

    const_iterator begin () const
    {
        return cObjects.begin();
    }

private:
    ...
    std::vector<C> cObjects;
};

That is to make you B a container or something like a container. This also completely encapsulates the implementation of B, code using B does not need to know that B uses a vector.

You could implement other operators, such as operator[] as required or at() to allow direct access.

Banfa 597 Posting Pro Featured Poster

Yes, you are partially right based on this assumption. But... why you choose that particular assumption ? Maybe we could choose this instead -
Let's assume that we don't have modern CPU and we are limited to very slow processor.
Don't you think that in this case "small savings" are also very important ?

I made the assumption just to show that unless you are willing to use a lot of memory the question of primeness is not relevant because it saves you nothing it only costs time. The fact that you can write an algorithm that uses less cycles at the expense of having a large data table I do not question.

If you want to assume that you don't have a modern CPU and cycles are important you will also need to assume that you don't have access to a modern amount of memory and there is no space for a 2.75Mbyte table :D Although small savings in both cycles and memory are important for such a platform.

Why you think so - that we should not teach How to optimize the code ? You think code optimization knowledge is not important at all ? You are clearly wrong. Try to make contemporary 3D shooter game on iPhone. In one way or the other you will be forced to optimize CPU cycles.

I think teaching optimisation is important but what you are talking about here is not an optimisation it is a trade off.

Banfa 597 Posting Pro Featured Poster

To start with learning to optimize CPU cycles without regard for memory usage is pointless. There will be times when memory usage is a larger consideration than CPU cycles and you have to be able to cope with both situations.

To me 2.75 Mbytes of memory is excessive for a single table (of course when I started you had to fit all your data into 65535 bytes) and the probability of your being able to type in such a large table without error is low (even if you use one of the on-line lists of prime numbers).

"ALL non-primes will never be factors of any number"
This is basically correct, it is certainly mathematically correct, but you must ask the following question which is how easy is it to determine that the value isn't prime? For instance is 34891 prime can it be skipped?.

Lets assume that we don't have the memory or preciseness required to create a large table of all required primes then it would have to be calculated.

As an example take the value 297, prime factors 3, 3, 3, 11, basically the algorithm does this

Try 2 - no 2s
Try 3 - found 3
Try 3 - found 3
Try 3 - found 3
Try 5 - no 5s
Try 7 - no 7s
Try 9 - no 9s *
Try 11 - found 11
Finish

* This is the …

Banfa 597 Posting Pro Featured Poster

This discussion has been moved from http://www.daniweb.com/forums/thread284115.html. Check there for the beginning.

= = = = = = = = = = = = = = = = = = = =

Actually neither approach is wrong.

The original code does not store prime numbers but does correctly identify all prime numbers although it does test some values such as 9 that are not required.

The approach suggested by 0x69 requires that you have already found all the prime numbers <= sqrt(userInput). This value is limited by the sizeof int so it is feasible to store all the require prime numbers in an array to facilitate factorisation.

The original code uses less memory but takes more processing (because it tests numbers that are not prime so can be part of the result), 0x69 solution takes less processing but takes more memory (on a 32 bit system enough to hold about 726800 prime numbers) because you have to store that table of prime factors.

So its a trade off, do you want to use an algorithm that uses less processing or one that uses less memory. And you can only really answer that question once you have decided what platform you will be running on and the limits of the algorithm you are writing (perhaps you only need to factorise numbers up to 500, that would reduce the memory requirement quite a bit).

However as I originally said neither algorithm is wrong it …

tux4life commented: Solid advice :) +8
0x69 commented: most neutral explanation here :-) +1
kvprajapati commented: N/A +9
Banfa 597 Posting Pro Featured Poster

Instead of outputting every time you find a prime factor you need to increment a count of the number of times you have had that prime factor. Then when you find a new prime factor output the data for the previous prime factor.

Banfa 597 Posting Pro Featured Poster

In your load function you call fgetc, that gets a single character from the file so for a number like say 10 it returns '1' which has the value 49. You then make a node out of the value 49 and continue making nodes out of every character in the file.

You need to read the whole number into an array of characters that is every digit until the next space which is what you have used as a separator. Actually using space as a separator makes things a little difficult, if you used newline '\n' as a separator then you could read the file something like this

char text[100];
int value;
int closeFile;

closeFile = (fgets(text, sizeof text, fpl) == NULL);
if (!closeFile)
{
    value = atoi(text);
    // Insert into list
}
Banfa 597 Posting Pro Featured Poster

A memory leak normally involves actually allocating memory and then forgetting to delete it.

Since I see no allocations I fail to see how you could be leaking memory.

Tell us what actual errors you are getting.

Banfa 597 Posting Pro Featured Poster

You shouldn't just output rgValue, it is binary data unless Type has a value of REG_EXPAND_SZ, REG_MULTI_SZ, REG_SZ.

If the value in the registry is really a DWORD then Type should be REG_DWORD and size1 should be 4 on exit. In that case something (non-portable) like DWORD dwValue = *((DWORD*)rgValue); should do the trick. Alternatively just pass a pointer to a DWORD into RegQueryValueEx in the first place if you are sure of the type the key holds.

RTFM: RegQueryValueEx

freemanirl commented: Yes! +0
Banfa 597 Posting Pro Featured Poster

C has absolutely no knowledge of folders and very little knowledge of files except in a generic sense.

However there is a distinction, C does provide a way to create and access files but provides no way to do the same for folders/directories.

Banfa 597 Posting Pro Featured Poster

There is no standard way to do this you will need to check your operating system library manuals.

In the WIN32 API there is CreateDirectory, however Linux will use something different as would .NET

Banfa 597 Posting Pro Featured Poster

Another useful addition I think:

On the quick reply box the is a shortcut button # for "Wrap code-tags round selected text". On the advanced reply box as well as # for code tags there is <Green Boxy Thing> for "Wrap code-tags round selected text".

Having the <Green Boxy Thing> button on the quick reply box would be an improvement, albeit a minor one.

Not quite sure what "TEX" is for so can't comment about that.

Banfa 597 Posting Pro Featured Poster

tests and RunExperiment are both members of Experiment so RunExperiment can access tests directly even though tests is private since this only stops access externally to the class.

tests is an array of pointers Test *tests[maxTests] so tests[0] has type Test* so to access the member of Test you would use tests[0]-><Member> .

Banfa 597 Posting Pro Featured Poster

You can use PlaySound to playback a wav file.

The actual contents can be a little complex because the data can be encoded in a number of different ways including mp3. However in its simplest form PCM it is actually very simple has it consists of an simple array of 8 or 16 bit integers.

The Wikipedia entry for WAV is a good place to start your research of WAV file format.

Banfa 597 Posting Pro Featured Poster

I do find the forum list entries have too much vertical height so that not enough list entries fit on the page. With a little tweaking with Stylish (on FF) I came up with the following (before and after shots).

Basically I

  • Reduced the font size by about 20%

  • Reduced the margin round each entry from 20px+(?) to 2px
  • Darkened the link that appears between each entry

To me this makes the forum list much more readable while still preserving, more or less, the new look and feel.

Banfa 597 Posting Pro Featured Poster

Another glitch

The "Unanswered Posts" tab of the forums is not working correctly (sorry if this has already been mentioned)

The "All Threads" tab remains highlighted and what is displayed is all threads.

Banfa 597 Posting Pro Featured Poster

Also, the left edge of the MMF box is too far left and the forums are cut off. Please align the edge of the button and the edge of the box.

OK someone tell me what is the MFF box? I think I know what it was on the old layout but I don't see anything light that on the new layout.


BTW is it me or has the general post rate taken a hit?

Banfa 597 Posting Pro Featured Poster

I am not convinced by this solution for instance line 17 can be replaced by

number /= i;
i -= 2;

which seems rather simpler and less wasteful of stack space.

The whole point of recursion, in my opinion is to remove iteration (loops) so way recursive function with a loop in it is suspect.

I think the returns look a little strange for a void function I would either leave the out or if I want explicit returns I would put them on the next line.

Banfa 597 Posting Pro Featured Poster

I have a suspicion that one of the problems is that the Post width has actually been made too large. When reading text the human eye can only go down the page so fast as you scan from the end of one line to the start of the next. This means that for very long lines of text you need extra space between the line or your eye overshoots the line. In the worst case you actually skip lines.

I don't think that Daniweb is at this worst case but I do think that the post lines are so long that the eye overshoots and has to correct upwards when it reaches the beginning of a new line making reading a strain.

This can be tested as currently Daniweb can be shrunk until it is about 930px wide by adjusting browser width (my screen res is 1280 x 1024) and at that width it seems to me that reading Daniweb gets easier on the eye.

On the old site that big margin for the side bar had the effect of doing this for you.

Tekmaven commented: This is a great point. You should be a usability expert! +0
Banfa 597 Posting Pro Featured Poster

Your input operator >> is not correctly parsing the input data.

To start with what if someone types a space before the equation, accessing the characters by direct offset is almost bound to cause an input error at some time. What if one of the numbers has more than a single digit.

Also you are storing the character value num.A = input[0] does not set num.A to the value 3 but rather sets it to the value '3' or 51.

You need to parse the input string, probably the easiest way would be to use a istringstream the following gets you started.

istringstream ss(input);

ss >> num.A;

Finally cin >> input; if a space is put in the equation then this will only get the first part of the equation because space is used as a field separator. You want to get the entire line with getline(cin, input);

Banfa 597 Posting Pro Featured Poster

Doesn't that bar down the bottom do pretty much all what you just said?

No it replaces 4 links with 1 that doesn't go to the page I want.

Banfa 597 Posting Pro Featured Poster

I can live with the colour scheme, I personally like purple and I can live with the changed layout or get used to it.

What is a pain is the drop in functionality of the main links.

What was

Today's Posts
--- C++
--- Software Development
--- My Subscribe Forums
--- All Forums

Has dropped to "Todays Posts" == Todays Posts All Forums

Same for Unanswered Threads

I now have to visit several pages to check all the posts I might have been interested in when I used to only have to visit 1.


And I agree each entry in the list takes far too much space, I should be able to look down the list an cherry pick the threads I am interested in but with only 2 visible without scrolling the page that is not possible. Even if I scroll the page there is only a maximum of 10 vertically displayed without scrolling further. Also the like to jump to the first new post in a thread appears to be missing from the listing page.

Banfa 597 Posting Pro Featured Poster

If you have ever used Excel with formulas in 1000s of cells then you would know that recalculation is very time consuming. In fact I had a sheet that had a few 100,000 cells filled in and I found that the best solution was to switch off automatic calculation and do a manual recalculate when I had finished all edits.

My point is recalculating everything is a brute force method but is quite common. You could try having each cell knowing what cells it is dependent on and only recalculating cells effected by the original change and any further changes that produces but you have to be careful, it is easy to get into an infinite loop that way if you have a circular dependency of cells.

You might try looking up the Observer Design pattern which might be of assistance.

Banfa 597 Posting Pro Featured Poster

For built in types you can not do this.

I suppose that you could create a class that referenced another value and used that as a basis to calculated the "value" of the class. However that would probably be very confusing to anyone reading your code and rather hard to maintain.

I think this is a question of should you do this rather than can you do this (which often occurs with C++) and the answer, in my opinion, is no you should not.

If you find you are often updating the value of b with a then perhaps the correct question is rather "is the design right?"

Could you find a better place to update the value of b or if it follows the value of a so closely could you eliminate it altogether?

Banfa 597 Posting Pro Featured Poster

It should never be considered "safe" to cast away a const, on some platforms const values are actually stored in constant unchangeable memory and trying to alter such a value can produce a processor trap. In fact I can not think of a time when casting away the cost is safe.

If you want to alter the value returned then take a copy of it and alter your copy. This is in fact what your code does since you have declare Bar P rather than Bar& P . You can always copy from a const because (generally) copying a value does not alter it.

Banfa 597 Posting Pro Featured Poster

Both lines 6 and 29 should definitely not have the void type, constructors do not have types.

The reason your output stream handler doesn't show the input is that the input stream handler writes to LineA but the output stream handler outputs valuea. Nothing in the called code converts what is read into LineA into a value in valuea.

Banfa 597 Posting Pro Featured Poster

@coded_hitec I believe the answer to your question is "no" but I would be happy to be corrected.

Banfa 597 Posting Pro Featured Poster

Basically you can resolve without using a pointer because a pointer (or reference) is the only thing you can declare in the presence of an incomplete type and either X or Y must be incomplete at the time the other is declared.

Any reason you don't want to use a pointer?

Banfa 597 Posting Pro Featured Poster

@Banfa
That essentially the Sieve of Eratosthenes

A-ha, I knew it had a name but as with so many algorithms I find it easier to remember how the algorithm works rather than its name. Which works fine except when I am trying to communicate with other programmers.

Banfa 597 Posting Pro Featured Poster

I see nothing wrong with it particularly so you are going to have to tell us what you want it to do and what it actually does since we have no knowledge of its indented purpose.

Banfa 597 Posting Pro Featured Poster

Sorry I am wrong about line 4, the compiler tries the available promotions then because the lhs is still unsigned it converts the rhs to unsigned and the comparison is performed on signed ints.

The expression in line 4 is false where as all the other expressions are true.

Banfa 597 Posting Pro Featured Poster

In lines 2 and 3 "1" can be promoted to int

in line 4 "1" can be converted to int

in line 5 "1" is already an int

In all cases the compiler compares the values using the int type, -1 is not converted to unsigned.

Actually I just checked the standard I will get back to you about line 4.

Banfa 597 Posting Pro Featured Poster

why would -1 be converted to unsigned int when (unsigned char) 1 can just be converted to int which has more width than unsigned char and is already the type of -1?

Did you mean to compare -1 and 1U?

Banfa 597 Posting Pro Featured Poster

No YOU are wrong, that is not 2 variables at the same address, that is a variable and a reference to the same variable. A reference is not a variable.

You can not have 2 variables at the same address, the standard specifically mandates against this.

You can not change the address of an object once it has been assign by the compiler.


You might be able to achieve what you want by using pointers

int a, c;
int *b = &c;

a = 10;
*b = 3;

// then later

b = &a;
Banfa 597 Posting Pro Featured Poster

for (j=0;j<2;i++) 3rd expression increment j not i

also you have mismatched braces countof { != countof }

Banfa 597 Posting Pro Featured Poster

The standard splits all expressions into 2 broad categories, lvalue and rvalue. The actual definition with-in the standard is rather involved but a simplistic rule of thumb is that an lvalue is an expression that results in a modifiable value where as an rvalue doesn't. Any lvalue can be converted to an rvalue but rvalues can not be converted to lvalues.

l and r stand for left and right colloquially and refer to where the expression can appear in relation to the assignment operator.

lvalue = rvalue - good
rvalue = rvalue - bad

You can assign to an lvalue because it is modifiable, you can not assign to an rvalue because it is not modifiable. Not that you can only assign from an rvalue but because all lvalues can be converted to rvalues that is not an issue. int array[5]; declares an array, and NOT a pointer. An array is an rvalue (where as a pointer is an lvalue) and can not be assigned to. This is one of the differences between arrays and pointers. Because an array is an rvalue array++; produces an error because the ++ operator requires an lvalue.

Banfa 597 Posting Pro Featured Poster

This is the error I get when putting "make miensfeld":
cc -Aa -g -c -o main.o main.c
<command-line>: error: missing '(' after predicate
make: *** [main.o] Error 1

Does anyone see the error?

No but since you left out most of the relevant information from the compiler error that is hardly surprising.

That error message contained the file name and line number when the compiler output it but you have seen fit to leave them out of your post. The error may not even be in main.c it could easily be, and probably is in my opinion, in another file included into main.c.

Next time I suggest you post the entire error message without editing it.

Banfa 597 Posting Pro Featured Poster

I'm sorry did you have a question or some compiler errors to post.

Also putting code tags round your code makes it more easy to read.

Banfa 597 Posting Pro Featured Poster

main returns int not void

The actual error indicates that the linker was unable to find the main to link to the start-up code.