Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

Is this a directory that you specify.

A directory I specify, as shown in the example program I posted. This might be another famous example where MSDN is wrong.

I decided to create unique filenames another way by using the current system time from GetLocalTime().

Thanks anyway for your reply.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

I would have written the first one like this

printf("|Val=%s",outString);

but if your goal is to concantinate two strings into a single buffer

char buf[255];

strcpy(buf,"|Val=";
strcat(buf,outString);

//or (same as above)
sprintf(buf,"|Val=%s",outString);

Neither of the above two are safe because neither strcat() nor sprintf() check for buffer overflow. Since you are using MFC you must also be using a c++ compiler. And in that case you should probably convert the code to c++ where it will be safer

std::string buffer;
buffer = "|Val=";
buffer += outString; // if outString is std::string then 
                            // you can combine the above 2 lines

;

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

By "user enters A" what exactly do you mean? one character? a whole string of characters? a number?

std::string buffer[5];
for(int i = 0; i < 5; i++)
{
  cout << "Enter string #" << i+1;
  getline(cin,buffer[i]);
}
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

did you try this

char buffer[6];
for(int i = 0; i < 5; i++)
   cin >> buffer[i];
buffer[5] = 0;

cout << buffer << endl;
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

what do you mean "it failes"? it won't compile? it won't run? what error(s) do you get? Note: unless its just a posting error, it needs a semicolor at the end of the cout line. Also, how is buffer declared?

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

most of the problems are typing errors -- such as using colon when semicolon is expected, and misspelled words. Using Dev-C++ I had to change the top like this: Note <iostream> without .h extension.

#include <iostream> // allows program to perform input and output

using namespace std; // program uses cout
//using std:cin; // program uses cin
//using std; endl; // program uses endl
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

_tempnam() always returns a filename in the "c:\\temp" directory, regardless of the parameters. This example was extracted from MSDN. I need to generate a unique filename in a directory other than c:\temp -- any ideas how to do that other than writing my own function? maybe a c++ solution?

Note this is one of may examples where Microsoft uses void main() instead of int main() :evil: Not that I mind -- but can be confusing to newbes.

Thanks

#include <stdio.h>

void main( void )
{
   char  *name2;


   /* Create a temporary filename in temporary directory with the
    * prefix "stq". The actual destination directory may vary
    * depending on the state of the TMP environment variable and
    * the global variable P_tmpdir.
    */
   
   if( ( name2 = _tempnam( "c:\\h", "stq" ) ) != NULL )
   {
      printf( "%s is safe to use as a temporary file.\n", name2 );
	  FILE*fp = fopen(name2,"wt");
	  fprintf(fp,"Hello World\n");
	  fclose(fp);
   }
   else
      printf( "Cannot create a unique filename\n" );
}
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

you cannot access class objects/methods from class static methods. There are at least two ways to overcome this:
1. pass a pointer or reference of an instance of the object to the static method, then access the objects through this pointer/reference.

2. make the object(s) static.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

How to decrease the amount of memory that a process/executable consume?

write less code :D look at the largest function(s) and see how (or if) they can be reduced.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

only write out the number of bytes read. At some point (at end-of-file) the number of bytes read will be less than the buffer size. This would go much faster if you read/write with larger buffer size -- say 255 characters.

int main()
{
	char buf[255];

	ifstream fp_in("my.txt", ios_base::binary | ios_base::in );
	ofstream fp_out("my_copy.txt",	ios_base::binary | ios_base::out);

	while (fp_in.read ( buf, sizeof buf ))
		fp_out.write (buf, fp_in.gcount() );
}
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

Here is a good one that is generic to any MS-Windows 32-bit compiler.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

ever hear of google

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

what dao classes are you using -- Microsoft MFC classes, some classes that you wrote, or something else? If something else then post a link to them.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

Your program is not what the question asked. It wants you to enter a 3-digit number all at one time, not one digit at a time. So your program should get the number as a string, then test each character of the string. Use fgets() to get they keyboard input.

char number[5];
fgets(number,sizeof(number),stdin);

Sure, that will let you enter anything, but at this stage of your programming you don't need to worry too much about that, just make sure you enter three digits. Once you get that working then you can "enhance" your program to include error checking (valid digits).

Convert a digit to its numeric equlivant by subtracting it from '0'

int n = number[i] - '0';

now in the above you can test n for odd or even.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

elements of an array are not called "records". A record is something you play on a phonograph machine, history of your activities in prison, or a complete collection of data in a file.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

schools should get their accrediations yanked and teachers fired for teaching such ancient compilers. There are much better free compilers such as Dev-C++. I'll bet MIT doesn't teach astrologers how to compute the distance of a star with a slide ruler and I know for a fact that NASA doesn't use them :)

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

yes, its true that with M$ compilers fopen and fstream eventually use win32 api functions. But there are a lot of reasons not to use win32 api for reading/writing text files and buffered i/o. Using either fstream or fgets() its really easy to read just one line of text (up to CR/LF), but win32 api its not so easy because you, the programmer, have to duplicate the functionality of fgets().

Bottom line: use win32 api directly only if speed is important to your program. Otherwise use either fstream or FILE and associated functions. Personally, I hate fstream because I think its ugly and very clumbsy. The only advantage is getline() used with std::string object. But for formatted i/o you can't beat the ease of fprintf() and fscanf().

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

It depends on the operating system you are using, and sometimes the database. In MS-Windows, the most common way of accessing databases is through the ODBC driver. You can use raw ODBC API functions or one of the serveral free c++ classes found by searching google

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

I find this amusing, especially after looking at his signature.

-Fredric

:lol: :lol: good catch!

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

Another option -- don't put any code in the constructor that might cause it to fail. M$ MFC is good at that -- first instantiate the object and then call its Create() method. The constructor only initializes class data to some default value (normally 0). Then the Create() method initializes all the rest and either returns a value or throws and exception.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

If you think your software is so great, you can spend a few million of your own money for packaging, advertisment, and distribution. Or, if you aren't quite that confident or wealthy, you can put it on the net as shareware.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

As for xor producing overflow: I do not see how xor produces overflow problems. Which is what my question was about (it wasn't about sorting): Does xor have problems when a negative number is involved that causes x ^= y; y ^= x; x ^= y; to not swap the values of x and y when x and y are not the same variable? That is, is there a hypothetical case of internal binary number representation and xor operation where a C or C++-compliant compiler would produce machine code that does not successfully swap, given certain strange values of equally-typed x and y?

The xor operator is commonly used in assembly language to set a register value to 0 -- xor if faster at that then moving 0 to the register.

xor does not have a problem with negative values of x or y because it treats x and y as unsigned integers.

Here is an example of the problem with using xor -- the result is 0 for all values of x.

#include <iostream>
using namespace std;

void swap(int& x, int& y)
{
	x ^= y; 
	cout << x << " " << y << endl;
	y ^= x; 
	cout << x << " " << y << endl;
	x ^= y;
	cout << x << " " << y << endl;

}
int main(int argc, char* argv[])
{
	int x = 2;
	swap(x,x);
	return 0;
}

This is the output

0 0
0 0 …
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

1) And if you do want to delete some attachment .. then you should go to your control panel --> select attachments from the left pane .. it'll show you all the attachments you've made .. select and delete your specfic ones ....

I don't have a delete button or option. maybe that's just a moderator option. I originally thought I read that there was a filespace limit -- but my eyes must have been crossed or something ;)

Thanks for your replies.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

...can u explain me this....

Nope. I don't know what taking the address of a function has to do with returning a value. constructors don't return values because c++ standards and language say they don't. ;)

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

>but the code seems to work ok.
Perhaps my wording was poor. If a and b refer to the same object, the result will be 0, regardless of what the original value was. Sure, you may argue that this is an unlikely event, but I've seen it fairly often, especially in sorting algorithms.

Oh you mean x ^= x?. I see your point about it not working when you want to swap the two values when they are both the same variable. swap function should never be called when the two variables are the same.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

post the program that saves the variables. Were the variables written in their ascii format or binary format? If ascii, did you put one or more spaces between them? of just jam them all up together. Open the file in Notepad or some other text editor -- can you distinguish the variable values?

If you want to read back an unknown number of integers (or other data type), read them one at a time and save them in a std::vector.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

Without special case tests, the XOR swap is hopelessly broken.

How? my compiler has no problems with it. Of course you can't see the difference if x = y, but the code seems to work ok.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

How is x ^= y; y ^= x; x ^= y; unsafe when x and y are equally sized integers? Is there a problem with using xor for signed integers?

it has the same overflow problem that my template has.

Well, I wouldn't really use it, because I've never swapped integers in my life.

Are you still a student? If not, how long have you been programming? Swapping integers (and other data types) is a common thing in sorting algorithms.

As for swapping strings, there is a member function named 'swap' which tends to achieve the task in constant time.

probably implemented like this

void swap(std::string& s1, std::string& s2)
{
   std::string temp = s1;
   s1 = s2;
   s2 = temp;
}

I know of no other way to do it with std::strings.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

i'll remind you of the func I was commenting on...
Obviously this is flawed. Cant you see that? It has potential for overflow and producing wrong results.

That was my first reaction too -- and yes, it does indeed produce overflow. But when tested with very large numbers -- INT_MAX from limits.h -- the template still produced the correct results with my compiler. I don't think there is a safe way to swap two integers without using a temp variable.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

I agree that allocating a larger buffer is not going to solve all the world's problems, but it will solve the problem of the OP by using the "memory is cheap" approach. sprintf() and other similar C functions need as large of buffer space as you can give it. Giving it too small buffer will cause large headaches.

For that reason, programmers who use c++ compilers that support STL (and not all of c++ compilers do) should not even use those C functions, but use std::stringstream and std::string instead. Those class will avoid all those memory problems, unless you want to suck-up every byte you can out of your program. That is a general rule, and there are many cases where c-style character arrays cannot be avoided.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

>
What are you babbling about? Your template function cannot swap strings, so why are you talking about strings? I get the feeling you're in the wrong thread.

Yup. got my threads confused :D

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

no it doesnt work you disregard any overflow errors. That to me makes it superflawed!

That was aimed at ancient dragon on his template swop two numbers function.The perils of replying before reading page 2

[edit]my stupid comments deleted because they were for wrong thread :sad: [/edit]

Page 2 didn't exist when I posted that.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

>And why do you think it is sooo stupid
Because it's useless trivia. Questions like this are basically like tricky riddles: unless you already know it, you probably won't figure it out on your own. You also won't use it in the real world.

yes, its a trivia question, but one that will separate the real programmers from the dabblers, the chaf from the weat, the men from the boys, thinkers from the robots -- you get the idea :) It teaches creative thinking, and isn't that one of the goals of higher eduational instutions?

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

Probably because the are not explicitely called in your code, so what good would it do to return a value -- nobody is going to be listening.

The constructor is only called when you instantiate an object. There is no way to catch the return value of the constructor.

// This doesn't make sense!!
int x = CMyClass SomeObject;
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

>To quote the boss: "Memory's Cheap"
Your boss is clueless. Yes, memory may be cheap, and these days there is a lot of it. However, that doesn't change the fact that if you use too much, you'll page into virtual memory and your program will grind to a screeching halt. Also, the more memory you use, the greater your chances of encountering excessive cache misses and noticeably slowing your program.

So yea, memory is cheap, but there's also no such thing as a free lunch.

Well, you have to be practicle about it. One wouldn't allocate 10 mg buffer just to hold 16 bytes! "memory is cheap" means you don't have to be too stingy about allocating a few more bytes of memory than needed. Such was the case in the OPs erxample -- one byte too few can cause days or weeks of debugging (been there, done that!). Just allocate one or two more bytes than really needed will save slitting your wrists trying to find the bug.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

>
>2.Exchange two numbers without using a temporary variable.
Translation: Explain why exchanging two numbers without a temporary variable is the height of stupidity.

And why do you think it is sooo stupid (unrelated to you comments about use of macros, which I agree with)? Did you read the template I posted (not my original code)? works with integers, floats and doubles. Won't work with c++ classes or C-style strings. I think the only way they can be swapped is via temp variable.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

Now you got me started, for swapping either integers or floats this will work too ...

Starting with your example, you could use a c++ template.

#include <iostream>
#include <limits.h>
using namespace std;

template<class T>
swapm(T &a,T &b)
{
	a = a + b;
	b = a - b;
	a = a - b;
};

int main()
{
    int a = 1;
    int b = 7;
    
    cout << "a = " << a << "   b = " << b << endl; 
	swapm(a,b);    
    cout << "a = " << a << "   b = " << b << endl; 

    
	float c = 1.23F;
	float d = 2.34F;
	
    cout << "c = " << c << "   d = " << d << endl; 
	swapm(c,d);    
    cout << "c = " << c << "   d = " << d << endl; 

    cin.get();   // wait
    return 0;
}
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

I assume you are writing a C program, not C++. If this is a c++ program then you should not be using C-style buffers at all -- use std::string and std::stringstream.

One way to avoid buffer overflow is to make the arrays bigger -- there is nothing at all wrong with having buffers that are a little bit bigger than needed. So what if you waste a few bytes (unless you are allocating thousands of those structures) -- that is a lot better than too small buffers which cause buffer overflows.

you don't have to set each element of the array individually like you show. Just do it like this

sprintf(foo.array2, "00:00:%9f", diff/(1.0e6));
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

This is a simple example of how to use recursion to get a list of all the directories (folders) and file names within them. It also illustrates simple use if std::list, std::vector, std::string, std::cin and std::cout. It was compiled and tested with both VC++ 6.0 and Dev-C++ compilers on XP Pro.

// The next two lines are for VC++ 6.0 compiler.  You should 
// delete them if you compile it with a different compiler.
#include "stdafx.h"
#pragma warning(disable: 4786)
#include <io.h>
#include <string>
#include <vector>
#include <list>
#include <iostream>
using namespace std;


// structure to hold a directory and all its filenames.
struct FILELIST
{
	string path;
	vector<string> theList;
};


void TransverseDirectory(string path, list<FILELIST>& theList)
{
	struct _finddatai64_t data;
	// First create the filename that will be use to initialize the find.
	// "*.*" are wild card characters that tells the find function to return a 
	// list of all the files and directories.  You can limit this if you wish
	// to just file with specific extensions, for example "*.txt".  If you do that
	// then finder will not return any directory names.
	string fname = path + "\\*.*";
	// start the finder -- on error _findfirsti64() will return -1, otherwise if no
	// error it returns a handle greater than -1.
	long h = _findfirsti64(fname.c_str(),&data);
	if(h >= 0)
	{
		FILELIST thisList;
		// add empty FILELIST structure to the linked list argument
		theList.push_back(thisList);
		// get pointer to the FILELIST just added to the linked list above.
		list<FILELIST>::iterator it …
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

Dave -- why are you being so polite and nice? just delete this offending thread :)

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

Ok now for a third question

If it's not apparent to you where to place your question after browsing through the various levels of the menu system here, you can feel free to ask for assistance in the 'Introductions' section of 'Coffee House'. That's part of the reason we have that section

Is that information now obsolete?

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

gcc will never work under DOS, it's 32 bit only ;)

Yup -- Narue already gave me a bloody nose for that one :mrgreen:

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

1. Once we have attached something to a thread is there any way to delete the attachment at some later date? since we have a limited amount of space for attachments how do we clean this up for future use?

2. I added a new contribution to Code Snippets but it doesn't show up there as fast as it does in the forums. Does one of the mods have to review and post it?

Thanks

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

hello sir

I realize you mean well, but there are a few women here too. And this isn't the Navy where both men and women officers are called "Sir". No need to be so stiffly formal on any of these forums. :D

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

The results of that program is unpredictable, undefined, and compiler implementation dependent. So one compiler may give one result while another compiler may give other results. why? because the compiler may, or may not, push the results of the pointer operations onto the stack after each operation. Its entire possible and conceivable that only the final result of ptr will get pushed onto the stack before print function is called.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

This might help -- shows different file formats.

NicAx64 commented: thanks for the site , I everyday learning something by digging your thread ha ha ! +1
piriyanka commented: super good +0
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

you are quite right -- I should have said MS-Windows, not MS-DOS (which is almost, but not quite, a dead os). That was just a slip-of-the-fingers :)

Never heard of Textpad program. I'll google around for it. I do all my programming with Microsoft tools (VC++ 6.0 and eVC++ 3.0/4.0 compilers). I love vi when doing *nix programming, which isn't all that often.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

In the link to Shell Programmer's Guide, navigate to the link Shell Basics: Extending the Shell.

Here is some more information (tutorials) that may be helpful. But you need a farily good grasp of C and C++ languages.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

you need to make Size() method const

inline int Size() const;                        //to find the length of pData;
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

Comeau may be a conforming c++ compiler but it contains no C support, no standard libraries either C or C++ and no STL. You have to get all that from someplace else. And as far as I can tell it is only command-line driven c++ compiler with no IDE -- no big deal for *nix programmers because they work in the ancient past anyway.

For MS-DOS, the best FREE conforming compiler is Dev-C++ from bloodshed.net. There are better compilers, but they are not free.