Trying to create a vector using a structure definition as the basis in VC++ - Page 2
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 2 of 3 FirstFirst 123 LastLast
Results 16 to 30 of 38

Thread: Trying to create a vector using a structure definition as the basis in VC++

  1. #16
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,571

    Re: Trying to create a vector using a structure definition as the basis in VC++

    I don't want to interfere with all the things that already have been stated correctly, but I think I should clarify (at least superficially) some things about the relation between native C++ and managed C++ (IOW C++/CLI) before even more confusion arises...

    Quote Originally Posted by 2kaud View Post
    If Friedman is the name of the "solution/project" then this is not a namespace and hence

    using namespace Friedman;

    is incorrect and should not be included.
    That's not exactly true for Windows Forms application projects. When the VC++ IDE sets up such a project, it creates a namespace with the same name as the as the project. I usually call that the "application namespace", but I think that's by no means an official term. The main form class (Form1) is defined in that namespace, but for any other classes (except for forms created by the IDE), the developers need to take care of that themselves.

    Quote Originally Posted by Paul McKenzie View Post
    How are you going to learn the advanced topics if you don't know the basics, such as namespaces? You can't cherry-pick certain topics in C++ and expect to get anything useful done. You have to know the basics before going on to do anything else in C++.

    [...]
    So true, so true... While not even native C++ really is a language meant for beginners, C++/CLI is even less. One might say that C++ is a language for those who know what they're doing, and C++/CLI is one for those who know even better. (By which I don't mean to say that C++/CLI is in any way superior to native C++. But it definitely is more demanding in some aspects.)

    One word directly to the OP, Protocol: MFC is sort of the canonical way of writing native C++ Windows GUI apps, but the Express Edition doesn't provide that. So the only way to write Windows GUI applications with the Express, except for Petzold-Style raw Win32 programming (rather tideous) or 3rd-party libraries, is Windows Forms. But if you pick that, stick with it. Mixing managed and native code in C++/CLI is possible, and in fact the probably primary advantage of C++/CLI, but it's strongly discouraged unless you have a really good reason to do that, especially for beginners. Such combinations result in "interop scenarios" which can be really, really advanced and cause unexpected and complicated difficulties.

    If you make your decision for Windows Forms and C++/CLI, feel free to post in the dedicated forum section. But, as already mentioned, I strongly recommend against mixing that with native C++ without a good reason.
    Last edited by Eri523; January 27th, 2013 at 10:41 PM. Reason: Small but important semantic fix
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  2. #17
    Join Date
    Feb 2005
    Posts
    34

    Re: Trying to create a vector using a structure definition as the basis in VC++

    Thanks for actually going so far as to run this code through your compiler. (I don't understand how your middle term would work to pass meaningful data to the function. It looks like a memory address is defined in the function, but you pass the name of the vector of structured data.)

    I've tried a few things tonight. Although they compile, they do not produce any data saved in the output file that is predictable. I'd expect to see 188 and 366 separated by a comma in five, vertically stacked lines of data pairs. What I get looks like digital noise from the memory, instead, when I compile the following.

    HEADER:

    Code:
    #ifndef EINSTEIN_H
    #define EINSTEIN_H
    
    #include <stdio.h>
    #include <vector>
    using namespace std;
    
    
    struct SizeAll{
            double year;
            double R;
            SizeAll() { year = 0; R = 0; }
            };
    
    
    typedef vector<SizeAll> SizeVector;
     
    
    int write_to_file(int flag, SizeVector data, char const
    
    *fileName)
    {
    	int count = 0;
      FILE* fp;
      fp = fopen(fileName, "w");
      if (fp == NULL) return -1;
      
      while (count++ < flag) {
        fprintf(fp, "%d,%d\n", data[0].year, data[0].R);
    	//check for errors writing to file
    	if (ferror(fp)) return -1;
      }
      fclose(fp);
      return 0;
    }
    #endif
    LOADING HEADERS INTO MAIN

    Code:
    // Friedman.cpp : main project file.
    
    #include "stdafx.h"
    #include <vector>
    #include <stdio.h>
    using namespace std;
    #include "Einstein.h"
    #include <math.h>
    
    
    #include "Form1.h"
    using namespace Friedman;
    CALLING ROUTINE

    Code:
    int counter=0,year=0,retval=0,count=0;
        SizeVector Universe;
    	Universe.resize(5);
    	SizeVector *heretis;
        char const NameFile[]="D:\\Friedout.csv";
    	
    	heretis=&Universe;
        Universe[0].R = double(366);
        Universe[0].year = double(188);
    		for ( counter = 15000 ; counter > 99 ; counter-- )
    		{
            
    			if (counter==100)//||counter ==2500||counter==5000||counter==7500||counter==10000||counter==12500||counter==15000)
    			{
    		
    			//Universe[count].year =double(counter);
    			//Universe[count].R = double(counter*2);
    			count = count + 1;
    			retval=write_to_file(5, Universe, NameFile);
    				if (retval ==-1) 
    				{
    				break;
    				}
    			}
    		}

  3. #18
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,571

    Re: Trying to create a vector using a structure definition as the basis in VC++

    You're still using the wrong format specifier in your fprintf() call. %d is for integers, not for doubles.
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  4. #19
    Join Date
    Dec 2012
    Location
    England
    Posts
    2,005

    Re: Trying to create a vector using a structure definition as the basis in VC++

    Why would you expect to see the output you want? The program doesn't do this!

    Your specific assignments

    Code:
    Universe[0].R = 366.0;
    Universe[0].year = 188.0;
    are overwritten by

    Code:
    Universe[count].year = double(counter);
    Universe[count].R = double(counter * 2);
    as count starts at 0!

    Assuming you use the right format specifier in fprintf, the data you'll get in the file is

    15000.0,30000.0
    15000.0,30000.0
    15000.0,30000.0
    15000.0,30000.0
    15000.0,30000.0

    which is correct for your program logic!

    In the function definiton

    Code:
    int write_to_file(int count, const vector<SizeAll>& data, char const *fileName)
    data is being passed as a reference - not as a memory address. This is a c++ concept. As Paul has repeatly stated

    you can't cherry-pick certain topics in C++ and expect to get anything useful done. You have to know the basics before going on to do anything else in C++.
    The code that produced the above output is
    Code:
    #include <vector>
    using namespace std;
    
    struct SizeAll {
        double year;
        double R;
    
        SizeAll() : year(0.0), R(0.0){};
    };
    
    typedef vector<SizeAll> VecSize;
    
    int write_to_file(int count, const VecSize& data, char const *fileName)
    {
    FILE*	fp;
    
    	if ((fp = fopen(fileName, "w")) == NULL)
    		return -1;
    
    	while (count--) {
                fprintf(fp, "%.1f,%.1f\n", data[0].year, data[0].R);
    
    	    //check for errors writing to file
    	    if (ferror(fp))
    		return -1;
    	}
    
    	fclose(fp);
    	return 0;
    }
    
    int main()
    {
    int    counter,
    	retval,
    	count=0;
    
    char const NameFile[]="d:\\Friedout.csv";
    
    VecSize	Universe(5);
    
    	Universe[0].R = 366.0;
            Universe[0].year = 188.0;
    
    	for ( counter = 15000 ; counter > 99 ; counter-- ) {
    		if (counter == 100 || counter == 2500 || counter == 5000 || counter == 7500 || counter == 10000 || counter == 12500 || counter == 15000) {
    			Universe[count].year = double(counter);
    			Universe[count].R = double(counter * 2);
    			count++;
    			retval = write_to_file(5, Universe, NameFile);
    			if (retval == -1)  {
    				break;
    			}
    		}
    	}
    	return 0;
    }
    Hope this helps.

  5. #20
    Join Date
    Feb 2005
    Posts
    34

    Re: Trying to create a vector using a structure definition as the basis in VC++

    I truly appreciate your responses.

    I'll work on the code later on today and let you know if the modifications you suggest repair the problem.

    I'd like to build a grasp of working techniques in code that functions, from which I can borrow methods for use in the future. I last tried C++ with CodeWarrior for Palm. I found that after a while I was no longer going to the forum for that software and was developing the program rather smoothly. At that time I learned quite a bit about issues of instantiating and freeing up memory space with variables while debugging in the Palm emulator.

    I've tried a little Borland Builder C++, but that went down the tube with Borland, and I couldn't justify spending fifteen hundred dollars for the professional edition with no anticipation of programming professionally. I saw that Microsoft had a free version of VC++, and decided to use it.

    I did complete one graduate course in C++ as directed study to produce a template base class to perform matrix manipulation. That was in 1997. Things have happened since, and my memory is not what it was immediately after I completed the MSEE. Sorry if I seem to be a bother, but I do appreciate your assistance. (I was a little too tired last night to dig into the logic of the code after it compiled.)

    I've lost a lot of what I once knew with regard to C++ after writing that template class. Typically I regain it if I focus on developing code for a while, but it fades in the subsequent years, and I'm back to where I am now.

  6. #21
    Join Date
    Feb 2005
    Posts
    34

    Re: Trying to create a vector using a structure definition as the basis in VC++

    Oh great 2kaud! You seem to have failed to quote from the very post of mine that contains the changes that made me anticipate the outcome that I referenced, although you did read the portion in which I express my disappointment due to the result being unpredictable! Instead, you quote from slightly more stale code below! No worries... Your time is valuable, and such minor points don't bother me a bit given your clever insight. Why read another long code statement if you've already brilliantly determined the true cause of the unpredictability?

    Quote Originally Posted by 2kaud View Post
    Why would you expect to see the output you want? The program doesn't do this!

    Your specific assignments

    Code:
    Universe[0].R = 366.0;
    Universe[0].year = 188.0;
    are overwritten by

    Code:
    Universe[count].year = double(counter);
    Universe[count].R = double(counter * 2);
    as count starts at 0!

    [/CODE]

    Hope this helps.
    Yes, great 2kaud! It helped! It solved the problem. I needed merely to insert your format mask, and what happened? The code ran predictably. (See, I'm even remembering terms like "mask" on only my second day with the software...) I'd experimented with "%d" and "%f", and only seen that the results eliminated the decimal in the former. That was fine, since I'm dealing with billions of years in the output, and massive volumes. I do need to find an easily comprehensible reference on output formats that include "%lf", because I don't specifically recall using that one in the past, although the C instructor probably managed to slip it in somewhere, two decades ago.

    I used your output format for the file:

    Code:
    fprintf(fp, "%.1f,%.1f\n", data[0].year, data[0].R);
    and it ran like a charm!

    All hail, 2kaud! Insightful! Helpful! Radiant keeper of C++ useful brilliance, divine software insight, and Olympian Coder (or "OC" for short)!

    (Okay, maybe that was a little thick...)

    Thank you!

  7. #22
    Join Date
    Apr 1999
    Posts
    27,418

    Re: Trying to create a vector using a structure definition as the basis in VC++

    Quote Originally Posted by Protocol View Post
    I needed merely to insert your format mask, and what happened? The code ran predictably.
    If you used C++ streams, then there is no issue of using the correct format statement.
    Code:
    #include <fstream>
    //...
    std::ofstream outfile("name_of_output_file");
    //...
    outfile << data[0].year << "," << data[0].R;
    The printf() family of functions are discouraged from use due to being non-typesafe, leading to runtime errors. The streams automatically convert the type to the appropriate string to be outputted.

    Also, gcc has made free compilers for many years now. You never needed to spend money on Borland Builder or any such compiler when there was a completely free one (that is used in many commercial programs and by many companies) out there all along.

    Regards,

    Paul McKenzie

  8. #23
    Join Date
    Feb 2005
    Posts
    34

    Re: Trying to create a vector using a structure definition as the basis in VC++

    If anyone knows of a particularly good (free) downloadable e-book (in pdf, or e-book format) that I might download on programming in C++ that is compatible with VC++ and offers fundamental guidance relative to how to build code in C/C++, would you please pass the web link along? I have a slow internet connection, and the VC++ help for my express version of the software simply sends me to the Microsoft Developer website. It might be useful to have a searchable e-book on my desktop in which I can seek guidance next time I need to select an output mask...

    I have one, Borland, programming in C++ for Windows books left on my shelf, and it is decades out of date. (I have three books on programming for Palm OS - but that pesky Android OS just HAD to come along... I should probably re-assign myself the problem of writing a template base class and try to work my way back through it again.)

    Thanks to all who helped out here!

  9. #24
    Join Date
    Dec 2012
    Location
    England
    Posts
    2,005

    Re: Trying to create a vector using a structure definition as the basis in VC++


  10. #25
    Join Date
    Feb 2005
    Posts
    34

    Re: Trying to create a vector using a structure definition as the basis in VC++

    1. Thanks, I'll take a look, but if anyone has already done that and knows of a particularly insightful e-tome that I can download on C/C++ (or VC++), I'd certainly appreciate the name and link.

    2. I started working on this software again this morning after spending yesterday helping an elderly relative get out of the house for a little while to attend to some personal matters. I was able to produce a file that contained all but the highest valued output just as I wanted it, but I could not induce the code to generate the highest valued output. Now the code is simply locking up and producing no file. (I had thought it was continuing to generate a file each time that I tweaked it, but found that, instead, only the first file remained on my "D:" drive directory.)

    I know that with VB it was not that difficult to debug the code in a mode that let me induce the IDE to mark each line of code as it was being executed while testing. That enabled me to find the point at which the errors were occurring or where the code was trapped in a loop. I'd prefer to only trace code lines after the build, rather than each line related to generating a form produced as managed code by VC++. Can anyone advise me with regard to the proper approach by which to cause VC++ (express) to first build the file, then begin to trace the code lines as they are implemented on-screen? (I'll add the latest version of my code below, in case anyone cares to seek the error simply via inspection. I'll be further along and more insightful in terms of being able to see where my code is going wrong when I can again "watch" variable values and concurrently see each line of the code indicated that is executed marked on-screen while debugging, as I did with VB 5.0. I tried to put a variable in the "watch" window, but because VC++ was busy building the file, I had to step through a great deal of managed code that was being executed while that variable was "out of scope" for the code that was being run by VC++.) Thank you.

    "Main.cpp" code header file load follows

    Code:
    // Friedman.cpp : main project file.
    
    #include "stdafx.h"
    #include <vector>
    #include <stdio.h>
    using namespace std;
    #include "Einstein.h"
    #include <math.h>
    
    
    #include "Form1.h"
    using namespace Friedman;
    ROUTINE THAT CALLS FUNCTION IN EINSTEIN.H TO PRODUCE OUTPUT CSV FILE

    Code:
    //BEGINNING OF CODE WRITTEN TO IMPLEMENT COMPUTATION
    
    int counter=0,year=0,retval=0,count=0;
        SizeVector Universe;
    	Universe.resize(7);
    	SizeVector *heretis;
        char const NameFile[]="D:\\Friedout.csv";
    	
    	heretis=&Universe;
    	for (count=0;count=6;count++)
    	{
        Universe[count].R = double(0);
        Universe[count].year = double(0);
    	}
    	count = 0;
    		for ( counter = 15000 ; counter = 100 ; counter-- )
    		{
    			if (counter==100||counter==2500||counter==5000||counter==7500||counter==10000||counter==12500||counter==15000)
    			{
    			Universe[count].year =double(counter);
    			Universe[count].R = double(counter*2);
    			count = count++;
    				if (retval ==-1) 
    				{
    				break;
    				}
    			}
    		}
    		retval=write_to_file(6, Universe, NameFile);
    
    
    //END OF CODE TO COMPUTE VALUES AND CALL FILE STORAGE ROUTINE


    EINSTEIN.H HEADER FILE WITH ROUTINE TO PRODUCE OUTPUT CSV FILE

    Code:
    #ifndef EINSTEIN_H
    #define EINSTEIN_H
    
    #include <stdio.h>
    #include <vector>
    using namespace std;
    
    
    struct SizeAll{
            double year;
            double R;
            SizeAll() { year = 0; R = 0; }
            };
    
    
    typedef vector<SizeAll> SizeVector;
     
    
    int write_to_file(int flag, SizeVector data, char const*fileName)
    {
      int Ecount = flag;
      FILE* fp;
      fp = fopen(fileName, "w");
      if (fp == NULL) return -1;
      
      while (Ecount-->-1) {
        fprintf(fp, "%.1f,%.1f\n", data[Ecount].year, data[Ecount].R);
    	//check for errors writing to file
    	if (ferror(fp)) return -1;
        }
      fclose(fp);
      return 0;
    }
    #endif
    Last edited by Protocol; January 27th, 2013 at 11:06 AM.

  11. #26
    Join Date
    Dec 2012
    Location
    England
    Posts
    2,005

    Re: Trying to create a vector using a structure definition as the basis in VC++

    Do you really mean this?

    Code:
    for ( counter = 15000 ; counter = 100 ; counter-- )
    which sets counter to 100 every time it trys to go round the loop and always returns true so the loop never terminates!!

    or do you actually want

    Code:
    for ( counter = 15000 ; counter >= 100 ; counter-- )
    which checks that counter is >= 100?

  12. #27
    Join Date
    Feb 2005
    Posts
    34

    Re: Trying to create a vector using a structure definition as the basis in VC++

    I was trying to use the VB concept for "For Count = 1 to N" re-syntaxed as for (count = N; count =1; count --), to produce the same result but in reverse in terms of the values of "Count".

    This seems to be where the code is probably locking up (which is one reason why I requested some expert advice regarding how to initiate tracing AFTER the "build" and select watch variables at that time as well).

    Thank you once again "2kaud". Your consistent help in this topic is much appreciated. (The Boolean issue did occur to me this morning, but identifying the loop by learning how to turn on the trace seemed like a reasonable next step before I began to confirm the relevance of the construction of the loop's controlling symbols.)

    Note: I still need to learn how to trace through the code while debugging and how to set watch variables AFTER the code has been built (so I can identify a specific loop in which the program becomes trapped and focus my attention on the relevant syntax affecting control over it on my own).

    The code is still locking up even with this Boolean correction, so my inquiry regarding the trace option and watch variables remains relevant.
    Last edited by Protocol; January 27th, 2013 at 02:42 PM.

  13. #28
    Join Date
    Feb 2005
    Posts
    34

    Re: Trying to create a vector using a structure definition as the basis in VC++

    I searched MSN forums. Found "watch" variable thread. Set breakpoint, and after building code, waited until breakpoint was hit, then set the watch variable. Problem proved to be due to the "while-do" loop in "Einstein.h" header file. Had to change logical test to "> 0". Now it runs perfectly. I still need to decide how to handle the return of a "-1" from file writing function in "Einstein.h" before I move on to actually perform any meaningful calculations. I presume VC++ has some built in single line of code that can be used to send a simple error message to the screen with an "OK" box selection, to preclude the need to design a new form just for an error message to react to the return of an error value ("-1") from the file writing routine? I'll initiate an on-line search for that facility and the related syntax.

    Thanks again for all of your assistance!
    Last edited by Protocol; January 27th, 2013 at 05:52 PM.

  14. #29
    Join Date
    Dec 2012
    Location
    England
    Posts
    2,005

    Re: Trying to create a vector using a structure definition as the basis in VC++

    You have the same problem here. This loop will never terminate!

    Code:
    for (count=0;count=6;count++) {
        Universe[count].R = double(0);
        Universe[count].year = double(0);
    }
    This code is not needed anyhow as Universe elements are being overwritten later. Also, there is no need to pass the number of elements to write_to_file. The vector method .size() will return the number of elements in the vector.

    Why are you declaring heretis as a pointer to SizeVector????

    My revised code based upon yours is

    Code:
    #include <stdio.h>
    #include <vector>
    using namespace std;
    
    struct SizeAll{
            double year;
            double R;
            SizeAll() { year = 0; R = 0; }
            };
    
    typedef vector<SizeAll> SizeVector;
    
    int write_to_file(const SizeVector& data, char const *fileName)
    {
    FILE	*fp;
    
    size_t	count = data.size();
    
    	if ((fp = fopen(fileName, "w")) == NULL) return -1;
      
    	while (count--) {
    		fprintf(fp, "%.1f,%.1f\n", data[count].year, data[count].R);
    
    		//check for errors writing to file
    		if (ferror(fp)) return -1;
    	}
    
    	fclose(fp);
    	return 0;
    }
    
    int main()
    {
    int	retval,
    	count=0;
    
    SizeVector Universe(7);
    
    char const NameFile[] = "d:\\Friedout.csv";
    
    	for (int counter = 15000; counter >= 100; counter--) {
    		if (counter==100||counter==2500||counter==5000||counter==7500||counter==10000||counter==12500||counter==15000) {
    			Universe[count].year = double(counter);
    			Universe[count].R = double(counter*2);
    			count++;
    		}
    	}
    
    	retval = write_to_file(Universe, NameFile);
    	return 0;
    }
    This compiles and runs and produces the output

    100.0,200.0
    2500.0,5000.0
    5000.0,10000.0
    7500.0,15000.0
    10000.0,20000.0
    12500.0,25000.0
    15000.0,30000.0


    Note that in the function write_to_file you are passing the vector by value. This is very inefficent as every element of the vector is copied when the function is called. It is much better to pass the vector as a reference as per my code. I've use const as well as the function does not change the values of the vector.

  15. #30
    Join Date
    Dec 2012
    Location
    England
    Posts
    2,005

    Re: Trying to create a vector using a structure definition as the basis in VC++

    Our posts crossed! I was composing mine when you sent yours!

    The easiest way in Microsoft Windows to output an error message in a window on the screen is to use MessageBox. The MessageBox function creates, displays, and operates a message box. The message box contains an application-defined message and title, plus any combination of predefined icons and push buttons.

    int MessageBox(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType);

    For a simple error message, uType can be MB_OK and hWnd can be NULL. Thus an example would be

    MessageBox(NULL, "Body of message", "Title", MB_OK);

    You'll need to include windows.h for this (if it's not already included in stdafx.h). You said that you are using managed c++. I have no experience of managed c++ and implications of using MessageBox in that context.

    Have more fun!

Page 2 of 3 FirstFirst 123 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center