Narue 5,707 Bad Cop Team Colleague

>i know the output for the 1st case is wrong because it ends up showing in reverse
You're extracting the digits from least significant to most significant, and printing in the same order. Of course it'll end up showing in reverse. You need to figure out a way to store the digits so you can print them in the correct order, or extract the digits from most significant to least significant. For example:

#include <stdio.h>
#include <stdlib.h>

int main ( void )
{
  int value;

  fputs ( "Enter an integer: ", stdout );

  if ( scanf ( "%d", &value ) == 1 ) {
    double temp = value;
    int i;

    fputs ( "The digits are: ", stdout );

    for ( i = 0; (int)temp != 0; i++ )
      temp /= 10;

    while ( --i >= 0 ) {
      temp *= 10;
      printf ( "%d ", abs ( (int)temp % 10 ) );
      temp -= (int)temp;
    }

    putchar ( '\n' );
  }

  return 0;
}

>and the last case wont work
Of course not. If you get a calculator and do a manual run of the conversion loop, you'll see why too. What you need to do is prepend the extracted digit to your conversion value (because you're extracting the digits in reverse) using something like this:

int j;

for ( j = 0; n != 0; j++ ) {
  r = n % b;
  n /= b;
  sum += r * (int)pow ( 10, j );
}

Alternatively, you could extract the digits from most significant to least significant and append them to the conversion value.

Narue 5,707 Bad Cop Team Colleague

>void StringSearch(char String[], char Ch, char *Ptr);
The first rule of simulating pass-by-reference using pointers is that if you want to change the value of an object, you pass a pointer to it. You want to change the value of the pointer, not the character being pointed to, so you need to pass a pointer to the pointer:

void StringSearch(char String[], char Ch, char **Ptr);
Narue 5,707 Bad Cop Team Colleague

>as I understand this does not have the same function as .rfind.
Yes, yes it does.

>int index = str.rfind(" ", 3); //index should return 1
Correct.

>index = tot->LastIndexOf(" "); //Returns 4
Correct, but this isn't an equivalent call to the rfind call you compared with. If you use the overload of LastIndexOf that takes a starting index, and make that starting index 3, you'll find that it returns 1 as well:

#include <iostream>
#include <string>

using namespace System;

int main()
{
  std::string s1 = "1 23 56";
  String^ s2 = "1 23 56"; 
  
  Console::WriteLine( s1.rfind ( " ", 3 ) );
  Console::WriteLine( s2->LastIndexOf ( " ", 3 ) );
}

>If you will use LastIndexOf you are looking from the beginning of the string and not backwards.
I fail to see how you could think that when the documentation explicitly says this (for String::LastIndexOf(String)):

The search begins at the last character position of this instance and proceeds backward toward the beginning until either value is found or the first character position has been examined.

And this (for String::LastIndexOf(String, Int32)):

The search begins at the startIndex character position of this instance and proceeds backward toward the beginning until either value is found or the first character position has been examined. For example, if startIndex is Length - 1, the method searches every character from the last character in the string to the beginning.

Narue 5,707 Bad Cop Team Colleague

Presumably by go managed .NET you mean use the String class instead of std::string. If so, the LastIndexOf method is what you're looking for.

On a side note, do you even know that MSDN exists, or are you using the people on Daniweb as your personal programming reference?

Narue 5,707 Bad Cop Team Colleague

It's exactly the same:

List<List<String^>^>^ vec = gcnew List<List<String^>^>();

Don't forget to use gcnew for each of the sublists too, and feel free to simplify the syntax using typedef as has already been shown.

Narue 5,707 Bad Cop Team Colleague

>this is your function
Seeing as how the definition fails to match the one that ART01 has repeatedly demonstrated as the desired signature, I'd say it's not.

>If the array is full ( lenght == capacity ) then realloc is used to extend it's capacity
Assuming the array was dynamically allocated originally. Reading the first post, it's clear that the OP wants this function to work with a fixed array.

>*a = ( int* ) realloc ( *a, ( *capacity + ARRAYBLOCKSIZE ) * sizeof(int) );
What do you plan to do if realloc fails? As it is, your plan seems to be memory leaks and null pointer dereferencing.

Narue 5,707 Bad Cop Team Colleague

>Damn i didnt expect it to be that easy LOL!!
Because it's not.

>simply declared another array in the procedure with n+1
n isn't a compile-time constant, and C++ requires that particular attribute for array sizes. Your code is specific to a single compiler and will fail if compiled with another implementation that doesn't support the same extension in the same way. At the very least you need to use a dynamic array or std::vector.

>and copied elements of the array into it!
This fails to meet the original requirement of updating the array (which you claimed to be required and the function signature suggests). You cheated by assuming that callers want the values printed and nothing else. This lesser requirement could easily be met without introducing another array:

void proc ( int vett[],int n, int x, int y )
{
  for ( int i = 0; i < n; i++ ) {
    if ( vett[i] == x )
      cout<< y << x <<' ';

    cout<< vett[i] <<' ';
  }

  cout<<'\n';
}

>here is the code
Either your code doesn't solve the problem, or you completely failed to describe the problem correctly and have been stringing me along on a wild goose chase.

Narue 5,707 Bad Cop Team Colleague

>If you want to use modulo without floating points try (int)myFloat % (int)myOtherFloat
Brilliant, Holmes. Now show me how your idea works when myFloat is 0.5 and myOtherFloat is 0.3.

VernonDozier commented: Good counter-example +7
Narue 5,707 Bad Cop Team Colleague

Try creating a project instead of just a new file. You can add the existing .cpp file to the project, or delete it and add a new one once the project is created.

Narue 5,707 Bad Cop Team Colleague

>sorry what i mean wasnt remainder. is the decimal point.
>as in 5.7089 i wan it to show as 5 only.
Yes, that's a common mistake. :icon_rolleyes:

>i think i found the solution. using floor function?
That's one way, sure. Another is to cast to an integral type, in which case the precision is truncated (no rounding takes place). Yet another is the modf function, which comes in handy when you also need the precision, but not the two parts together:

#include <cmath>
#include <iostream>

int main()
{
  double d = 123.987;
  double i;
  double e;

  e = std::modf ( d, &i );

  std::cout<<"Splitting "<< d <<":\n";
  std::cout<< i <<'\n'<< e <<'\n';
}
Narue 5,707 Bad Cop Team Colleague

>well ofcourse the array is full since u have to first enter the array
Of course. :icon_rolleyes: I see you completely failed to see the multiple equally viable ways an array could be passed to your function, but thanks for clarifying your actual requirement.

>So whats ur opinion now that the array is full?
You're SOL. Sorry. Either you lose data by shifting it away, or you preserve data by failing in all cases.

Narue 5,707 Bad Cop Team Colleague

>ur first option i assume that u are stating a condition where
>if the array reaches its limit it will give u an error message?
Something to that effect, yes.

>now the prb is that if i have n(dimension of the array)
>how can i put the last element in n+1?
That's a problem if the array is full. By full I mean that when items are added, they're added in such a way that there are no holes between two items; all of the "unused" slots are contiguous and at the end. In that case, you can certainly shift and add as long as the number of items currently in the array is less than n.

Another situation is where there are holes in the array and the holes are initialized to some default value. In that case, you can only shift and add without losing values if the last value ( array[capacity-1] ) is a default value. But in that case you might not always needs to shift if the slot before X is a default value, then you can simply overwrite it with Y and be done.

Narue 5,707 Bad Cop Team Colleague

>i would like to display the output ot (top / 60) without the remainder and no rounding too.
That's two questions. You want to divide a floating-point value (just use the division operator, that works) and you want to display the value without rounding. The easiest way to do that (if you can manage it) is to increase the displayed precision such that cout doesn't round the value for you:

#include <iostream>

int main()
{
  double d = 123.4567;

  std::cout<< std::fixed << d / 10 <<'\n';
}
Narue 5,707 Bad Cop Team Colleague

>is there any to not show the remainder of a division?
Huh?

Narue 5,707 Bad Cop Team Colleague

The remainder operator doesn't work with floating-point types. Look up the fmod function in <cmath> for getting the remainder of floating-point division.

Narue 5,707 Bad Cop Team Colleague

>right?
Right. Well, the second one as the first is a syntax error. ;)

Narue 5,707 Bad Cop Team Colleague

Generally when working with arrays like this, you should be taking two size parameters: one for the number of filled slots, and one for the capacity. That way if the array is full you can throw a proper error. So option #1 is to change the way your function is called and do this:

void update ( int a, int size, int len, int x, int y )
{
  if ( len >= size )
    return;

  //...
}

Option #2 is to expect a dynamically allocated array so you can resize it, but a bunch of new problems can come up with this, like invalidating every pointer the caller has into the array and of course, requiring that the caller give you a dynamic array.

Option #3 is my preference, and that option is to ditch the array and use a std::vector object.

There are other options, but the get progressively more and more distasteful. ;)

Narue 5,707 Bad Cop Team Colleague

>Can´t Builder build and run my simple cpp old files?
Builder has no problem with standard C++. Quite likely your "simple" C++ programs aren't conforming to the standard, and thus are only guaranteed to work on the compiler that they were written with. Post your code and the errors Builder is throwing, somebody here can tell you what's wrong.

Narue 5,707 Bad Cop Team Colleague

>So there's a size mismatch.
And yet, the error doesn't say size mismatch, it says signed/unsigned mismatch. Your analysis is logical, but incorrect.

>why is it stated signed/unsigned mismatch when all
>variables are unsigned and no overflow is possible?
Because this is a case where the integral promotions can bite you. To summarize, both operands to the < operator are promoted using the integral promotion rules. i remains as is because its conversion rank is greater than int, so it continues to be an unsigned type. However, the result of x * y (unsigned short) has a conversion rank less than int, so that value is promoted to a type of int, which is signed.

[edit: Darnit, I hate getting interrupted while posting]

twomers commented: Interesting. Wasn't aware that conversion rank was involved, though I suppose it makes sense in retrospect. +6
Narue 5,707 Bad Cop Team Colleague

>How do I allocate memory for the paths pointer anyways? It is inside a struct.
It doesn't matter that it's in a struct. As long as the struct objects are created, you can do whatever you want:

node_routing_info global_routing_info[30];

for ( i = 0; i < 30; i++ ) {
  global_routing_info[i].paths = malloc ( 600 * sizeof ( path_info ) );

  /* ... */
}

>Besides, should I put global_routing_info on the heap too?
I don't see any reason why you should at this point.

>What happens if I don't?
You'll have 30 node_routing_info objects on the stack. Since paths is now a pointer, that's not nearly the hit that you had before, so it shouldn't be an issue.

Narue 5,707 Bad Cop Team Colleague

>Basically, there will be no difference.
Only if you ignore the fact that you can re-size a dynamic array. :icon_rolleyes: Start with a very small initial size and grow it by increments as you add paths. Or allocate the maximum possible size and once you've gotten all of the paths, shrink the size down to fit the actual number. Just because you don't know the number of paths before you fill the array doesn't mean you can't save space once you do know.

Narue 5,707 Bad Cop Team Colleague

1) Yes, you can allocate memory to a pointer regardless of it's level of indirection.
2) When you dynamically allocate memory, it's totally under your control. That means you must allocate enough memory, you must make sure it's resized properly, and you must make sure it's properly released when you're done.

>This is my exact problem
Yes, describing what you want is generally more productive.

>path_info paths[600];
If you want to use heap memory, you should make this a pointer and use malloc/calloc/realloc/free to maintain it:

typedef struct	//A row of the global routing table 
	{
        int                     node;
	int			no_paths;
	path_info	     *paths;
	}node_routing_info;

typedef struct	
	{
	int			path_id;
	int			length;		
	int			prev_hops[10];	     //maximum 10 hops per path
	}path_info;

node_routing_info	global_routing_info[30];	//no_elem= no_nodes.

If you have fixed values, a static array is fine. If you have an unknown number of values, or a maximum limit, dynamic arrays can often save you lots of space. You might also consider dynamically allocating prev_hops since it represents "up to N" hops and there might be a great many path_info objects. Since those objects will be on the heap, the stack overflow issue isn't as much of an issue, but you're still be using up memory and potentially affecting your performance.

Narue 5,707 Bad Cop Team Colleague

Yes, seeing as how your code is wrong (you try to use a data member as the return type), it clearly shouldn't compile. But returning a pointer to ArmorArray is quite trivial for you (unless I've misjudged your ability):

#include <string>

struct ArmorArray
{
  std::string armorName;
  int armorCheck;
  int maxDext;
  int price;

  ArmorArray *nxtArmor;
};

class Armor
{
private:
  ArmorArray ArmorList[13];
  ArmorArray *p_List;

  int m_SIZEARRAY;

  std::string m_ArmorName;
  std::string m_String;

public:
  Armor();
  ~Armor() {}

  ArmorArray *BuyArmor();
  std::string CreateString(std::string &myString);
  std::string ArmorBought(std::string &bought);
};

ArmorArray *Armor::BuyArmor()
{
  m_ArmorName = CreateString (m_String);

  for (int i = 0; i < m_SIZEARRAY; i++)
  {
    if(!m_ArmorName.compare(ArmorList[i].armorName))
    {
      return &ArmorList[i];
    }
  }

  return 0;
}

At first I thought you meant you wanted to return a pointer to an array and were struggling with the syntax, which is perfectly understandable.

JoBe commented: Thanks for the help, ... again. +4
Narue 5,707 Bad Cop Team Colleague

So, essentially you want to return a pointer to ArmorArray. What's the problem?

Narue 5,707 Bad Cop Team Colleague

>DoDMA(); //allocate memory for the headers
>BMPInfoHead = objCopy.BMPInfoHead;
>BMPFileHead = objCopy.BMPFileHead;
This strikes me as a memory leak. If DoDMA allocates memory to BMPInfoHead and BMPFileHead, you lose your only reference to the new memory by overwriting the addresses with this in objCopy.

>I'm looking for a fast, preferably 1 line, method of copying entire structs.
Assuming your structs are well defined for deep copying:

DoDMA();
*BMPInfoHead = *objCopy.BMPInfoHead;
*BMPFileHead = *objCopy.BMPFileHead;
Narue 5,707 Bad Cop Team Colleague

Seeing as how your posts follow the pattern of "Do it for me because I'm too special to learn", I've merged them into one thread so they can be more easily dismissed by the regulars.

Narue 5,707 Bad Cop Team Colleague

Same thing. Unless you're opening the System::Drawing namespace, you need to qualify all instances of Font as System::Drawing::Font.

Narue 5,707 Bad Cop Team Colleague

There's also a SelectionFont property:

this->richTextBox1->Select( 0, 10 );

Font^ current = this->richTextBox1->SelectionFont;

this->richTextBox1->SelectionColor = Color::Red;
this->richTextBox1->SelectionFont = gcnew Font (
  current->FontFamily, current->Size, FontStyle::Bold );
Narue 5,707 Bad Cop Team Colleague

There are two problems. First, you can't provide a pointer to a template, it has to be a pointer to an instantiation of the template. Translation: provide the template arguments:

Array<int> var = apply ( m, &sum<int> );

The second problem is that there's a mismatch between the function signature apply expects and the signature of the function you're actually passing. Specifically, the former doesn't take a reference as the parameter and the latter does. Fix your definition of apply such that fun takes a reference to Array<T>:

template<typename T>
Array<T> apply(Matrix<T> &m,T (*fun)(Array<T>&)){
  return Array<T>();
}
Narue 5,707 Bad Cop Team Colleague

Sort your vectors before merging.

Narue 5,707 Bad Cop Team Colleague

>do you see any problems with this code that would make that error?
Yes, and while I'm still miffed that you failed to post the complete text of your error even after I not so subtly informed you that more information is present, I'll tell you what the problem is:

merge(
  words.begin(), words.end(), // OK
  words2.begin(), words2.end(), // OK
  results.begin()); // Oops! results is empty

You need to use some kind of insert iterator to add new items to an empty vector, or you can resize the vector before calling merge:

merge ( 
  words.begin(), words.end(), 
  words2.begin(), words2.end(), 
  back_inserter ( results ) );

>You call the function with 5 parameters, but the function only expects 2
Can you say "overloading"?

Narue 5,707 Bad Cop Team Colleague

The error will also tell you what assertion failed and where it failed. Basically it means you used a library class or function the wrong way, such as passing a null pointer to strcpy.

Narue 5,707 Bad Cop Team Colleague

If you mean a complete reference of the standard library, I prefer Dinkumware. If you mean all libraries under the sun (as some bozos come here expecting), it doesn't exist.

Narue 5,707 Bad Cop Team Colleague

>Well personally I think its better suited than std::vector
Ignoring that valarray is designed for numeric types, and ignoring that you can't use the majority of operations with valarray on std::string, and ignoring that you've lost nearly all benefits of the standard library by using a bastard child of the standardization process, and ignoring that the standard definition is broken and many implementations of valarray are substandard because nobody cares enough to fix it in light of exression templates, it probably is better suited. But only for your specific example, and only after ignoring numerous rather large turds that you'll end up eating later.

There are certainly cases where valarray is a superior choice, but that's only because the interface is perfectly suited to the problem and a different solution would result in more complex code. However, this is not one of those cases.

William Hemsworth commented: Don't you ever get tired of being right :)?? +3
Narue 5,707 Bad Cop Team Colleague

>How about using std::valarray.
Why? That seems like a case of using valarray for the sake of using valarray. Kind of silly, in my opinion.

Narue 5,707 Bad Cop Team Colleague

>Works fine with VC++ 2005/2008
As it should. The code is correct, but I'm willing to bet that this is yet another bug in Visual C++ 6.0.

Narue 5,707 Bad Cop Team Colleague

What compiler are you using?

Narue 5,707 Bad Cop Team Colleague

Please use code tags and properly format your code. We'll give you a little leeway to learn how the forum works, but after a while (10 posts in general, but less if we feel you're intentionally refusing) you'll begin receiving infractions for breaking Daniweb's rules if you habitually fail to use code tags.

Narue 5,707 Bad Cop Team Colleague

>I do not know how to start the program!!
I always start with this:

#include <iostream>

int main()
{
}

>When it says "exponentially" then what formula should I use for the output?
The description says to double approximately every 24 months. Using that as the baseline, you can calculate the percent of total for the months entered versus the baseline and then calculate that percentage of the capability. Add the percentage of the capability to the base capability and you're done.

For example, you have a device that measures capability in flumpits. The starting flumpits come to 8, so in 24 months you can expect 16 flumpits because of the 24 month doubling. If you actually want to know the flumpits in some different span, like 18 months, you get the percentage of 18 in 24:

18 / 24 = .75 * 100 = 75%

Then add 75% of 8 flumpits to the current total:

8 * .74 = 6
8 + 6 = 14

So the growth of flumpits in 18 months would reach approximately 14 flumpits. What if you want to know the flumpits in 30 months?

30 / 24 = 1.25 = 125%
8 * 1.25 = 10
8 + 10 = 18

After 30 months you can expect an increase to 18 flumpits. This is a basic formula that should get you closer to finishing your assignment.

Narue 5,707 Bad Cop Team Colleague

>#define p printf
This is an extremely bad idea. If your teacher taught it to you, slap him for me.

>clrscr();
This is a bad idea. Not only is it anti-social (by removing the output of other programs when run in a shared console), it unnecessarily destroys the portability of your code.

>while(a>=1)
First, a doesn't have a predictable value. Second, how are you expecting to count from 1 to 100 with that condition?

>for(a>=0) p("%d",a);
I can't begin to guess what you were thinking here.

Here's a tip, and this is what I personally do when writing a new program, write out a bare bones main function with <stdio.h> and then add to it. Here's the bare bones code that I start with:

#include <stdio.h>

int main ( void )
{
  return 0;
}

Now add the parts you need. For example, you know you want to print the sum of 1 to 100, right? So add the framework for doing that:

#include <stdio.h>

int main ( void )
{
  int sum = 0;

  // Sum 1 to 100

  printf ( "The sum is %d\n", sum );

  return 0;
}

The point of this iterative approach is that you can test at every point. You can verify that your program prints the sum (even if it's always zero) at this point. At the previous point you could verify that the program runs and terminates properly. Now for the loop:

Nick Evan commented: great help for this newbie +9
Narue 5,707 Bad Cop Team Colleague

>but that is 12 bytes right? I need 12 bits.
Sorry, I misread your question. The smallest block of addressable memory you can use is a byte. If you need a bit count that isn't an even multiple of the byte size, you can either read "too much" and carry over the excess to the next operation using bitwise operators, or change your design to better fit the system.

>And should I open the file as ios::binary or not?
Yes, you should. That way you guarantee that textual conversions are not performed when you read the binary part. I imagine it's more important for the binary data be read correctly than the ASCII data. And you can always do manual newline conversions in the ASCII data if you need to.

Narue 5,707 Bad Cop Team Colleague

In other words, part of the file is ASCII and the rest is binary data.

>Can I do the above (ie. read with getline() and then read binary?
Sure, but you may encounter problems with newline conversion.

>How would I read 12 bits at a time (for a 12-bit color image)?
Use an array of 12 char:

char buf[12];

infile.read ( buf, sizeof buf );
Narue 5,707 Bad Cop Team Colleague

>so for a telephone directory will it be appropriate to use strcmpi() or stricmp() ?
That's a reasonable requirement.

Narue 5,707 Bad Cop Team Colleague

>in the underlined part, by greater value does it mean that A has greater value than B?
strcmp compares each character in order and returns the result of the first two characters that don't match. It's equivalent to this implementation:

int jcmp ( const char *a, const char *b )
{
  while ( *a == *b && *a != '\0' ) {
    ++a;
    ++b;
  }

  if ( *a < *b )
    return -1;
  else if ( *a > *b )
    return +1;

  return 0;
}

The final comparison is a direct comparison of the underlying integer value for the two characters. So "a" will be greater than "A" under ASCII because 'a' has a value of 97 and 'A' a value of 65.

This can sometimes be confusing if you're expecting comparisons for a natural ordering rather than lexicographical ordering by the underlying character set.

Narue 5,707 Bad Cop Team Colleague

>for misunderstanding the concepts of classes
That's hardly cause for an apology.

>is it really only to reuse code?
Classes are an organizational tool, nothing more. There are many, many ways you can use that tool to achieve many, many results, but at the core classes are just another way of structuring your code.

Narue 5,707 Bad Cop Team Colleague

Well, since you want to convert to little endian, I'll assume you have something in big endian format already. If that's the case it's a simple matter of reversing the bytes. For example:

void bswap ( unsigned int x )
{
  x = ( x >> 24 ) | ( ( x << 8 ) & 0x00FF0000 ) |
    ( ( x >> 8 ) & 0x0000FF00 ) | ( x << 24 );
}

Though ntohl and htonl are generally a better option if they're available.

Narue 5,707 Bad Cop Team Colleague

>Your right to a very small degree
That's a pretty arrogant statement, all things considered.

>But its still about 1000% faster.
Not on my system. I show a complete reversal of the timings, which means your code is also non-portable. Fancy that.

>I suppose a more in depth explanation could have been due earlier
Too late, you fail.

>but I didn't expect my code to face such scrutiny
You were planning on using that code essentially to prove that your instructor is incompetent. I have trouble seeing how not only you didn't expect close scrutiny by someone, but that you were also so sloppy as to completely fail such scrutiny both in describing the purpose of the code and writing the code itself.

>But I suppose it's appreciated ;)
Bite me. Nothing irritates me more than people dismissing my contributions with a smarmy comment. Don't expect any help from me in the future.

Narue 5,707 Bad Cop Team Colleague

Do you actually want to convert to little endian or is this some kind of homework project? Because converting to hexadecimal doesn't enter into the picture if you're working with the bytes. The representation only matters for display and such.

Narue 5,707 Bad Cop Team Colleague

You have three distinct problems.

1) You need to use square brackets instead of parentheses when dynamically allocating memory:

// Square brackets!
name = new char[strlen ( foo ) + 1];

2) You need to use the syntax for delete that matches the syntax for new:

base::~base()
{
  cout<<name<<"destructor called"<<endl;
  delete [] name;
}

3) You need to remember that assignment is different from copy construction. The following is all assignment:

t1 = b1;
t2 = b2 ;
t3 = b1+b2;

Yet you haven't defined an assignment operator. You can make it work by changing it to copy construction:

base t1 = b1;
base t2 = b2 ;
base t3 = b1+b2;
Narue 5,707 Bad Cop Team Colleague

>i am sorry
For what?