Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. Problem reading from text file

Problem reading from text file

Scheduled Pinned Locked Moved C / C++ / MFC
helpcsharpc++visual-studiographics
8 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • I Offline
    I Offline
    Ibrahim Bello
    wrote on last edited by
    #1

    OK, actually this program works fine, but only when run from Visual Studio. However, when I click on the .exe or launch it from windows command prompt, I get an error: "Unhandled exception at 0x775e59c3 in Materials.exe: 0xC0000005: Access violation reading location 0x54a075d8" and Windows shuts the program down. The Requirement The program is to read from a text file a list of tabulated data of a given material: Temperature, Density, Viscosity... etc. For example: Temperature Density Viscosity ... ... 50 0.2 0.3 ... ... 100 0.25 0.33 ... ... The aim of the program is to read these values (several) of them, store to memory and do some sorts of interpolations. I created a structure, each holding the properties of the material at a given temperature. I then dynamically create an array of structures based on the number of data. If I had 100 readings, I create 100 arrays to structure. .h file

    struct Material {
    float temperature;
    float density;
    float viscosity;
    };

    typedef Material* MATERIAL;

    The above go into the header file .cpp file

    MATERIAL* g_ptrMaterial; //global variable

    void ReadFile (char* filePath)
    {
    vector<string> Tokens;
    int i = 0;
    string val;
    char c;

    ifstream file(filePath); //instantiate and open file
    
    if (!file.fail())
    {
    	//cout << "Enter to begin...";
    	//cin >> c;
    	//cout << "Reading from File ...";
    	g\_numberOfRows = getNumberOfRows(file); //gets number of readings
    	g\_ptrMaterial = new MATERIAL\[g\_numberOfRows\];
    
    	getline(file, g\_fileHeader); //remove column headers i.e. Temperature, Density, etc
    
    
    	while (getline(file, val))
    	{
    		g\_ptrMaterial\[i\] = (MATERIAL) malloc(sizeof(MATERIAL));
    		
    		Tokens = GetTokens(val);
    		
    		if (!Tokens.empty())
    		{
    			//convertToFloat: converts string type to float type
                                g\_ptrMaterial\[i\]->temperature = convertToFloat(Tokens.at(0)); 	
    			g\_ptrMaterial\[i\]->density = convertToFloat(Tokens.at(1));
    			g\_ptrMaterial\[i\]->viscosity = convertToFloat(Tokens.at(2));
    
    			i++;
    		}
    	}
    }
    	
    else
    {
    	cerr << "FILE NOT FOUND!";
    	exit(1);
    }
    

    }

    //separates the input line into column readings
    vector<string > GetTokens (string val)
    {
    stringstream ss(val);
    string temp;
    vector<std::string > Tokens;

    while (ss >> temp)
    {
    	Tokens.push\_back(temp);
    }
    
    return Tokens;
    

    }

    Debugging What I di

    D _ K 3 Replies Last reply
    0
    • I Ibrahim Bello

      OK, actually this program works fine, but only when run from Visual Studio. However, when I click on the .exe or launch it from windows command prompt, I get an error: "Unhandled exception at 0x775e59c3 in Materials.exe: 0xC0000005: Access violation reading location 0x54a075d8" and Windows shuts the program down. The Requirement The program is to read from a text file a list of tabulated data of a given material: Temperature, Density, Viscosity... etc. For example: Temperature Density Viscosity ... ... 50 0.2 0.3 ... ... 100 0.25 0.33 ... ... The aim of the program is to read these values (several) of them, store to memory and do some sorts of interpolations. I created a structure, each holding the properties of the material at a given temperature. I then dynamically create an array of structures based on the number of data. If I had 100 readings, I create 100 arrays to structure. .h file

      struct Material {
      float temperature;
      float density;
      float viscosity;
      };

      typedef Material* MATERIAL;

      The above go into the header file .cpp file

      MATERIAL* g_ptrMaterial; //global variable

      void ReadFile (char* filePath)
      {
      vector<string> Tokens;
      int i = 0;
      string val;
      char c;

      ifstream file(filePath); //instantiate and open file
      
      if (!file.fail())
      {
      	//cout << "Enter to begin...";
      	//cin >> c;
      	//cout << "Reading from File ...";
      	g\_numberOfRows = getNumberOfRows(file); //gets number of readings
      	g\_ptrMaterial = new MATERIAL\[g\_numberOfRows\];
      
      	getline(file, g\_fileHeader); //remove column headers i.e. Temperature, Density, etc
      
      
      	while (getline(file, val))
      	{
      		g\_ptrMaterial\[i\] = (MATERIAL) malloc(sizeof(MATERIAL));
      		
      		Tokens = GetTokens(val);
      		
      		if (!Tokens.empty())
      		{
      			//convertToFloat: converts string type to float type
                                  g\_ptrMaterial\[i\]->temperature = convertToFloat(Tokens.at(0)); 	
      			g\_ptrMaterial\[i\]->density = convertToFloat(Tokens.at(1));
      			g\_ptrMaterial\[i\]->viscosity = convertToFloat(Tokens.at(2));
      
      			i++;
      		}
      	}
      }
      	
      else
      {
      	cerr << "FILE NOT FOUND!";
      	exit(1);
      }
      

      }

      //separates the input line into column readings
      vector<string > GetTokens (string val)
      {
      stringstream ss(val);
      string temp;
      vector<std::string > Tokens;

      while (ss >> temp)
      {
      	Tokens.push\_back(temp);
      }
      
      return Tokens;
      

      }

      Debugging What I di

      D Offline
      D Offline
      David Crow
      wrote on last edited by
      #2

      I did not find anything blatantly wrong with your code. The only changes I made to get it to compile in my environment were to change float to double and convertToFloat() to atof().

      "Old age is like a bank account. You withdraw later in life what you have deposited along the way." - Unknown

      "Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

      1 Reply Last reply
      0
      • I Ibrahim Bello

        OK, actually this program works fine, but only when run from Visual Studio. However, when I click on the .exe or launch it from windows command prompt, I get an error: "Unhandled exception at 0x775e59c3 in Materials.exe: 0xC0000005: Access violation reading location 0x54a075d8" and Windows shuts the program down. The Requirement The program is to read from a text file a list of tabulated data of a given material: Temperature, Density, Viscosity... etc. For example: Temperature Density Viscosity ... ... 50 0.2 0.3 ... ... 100 0.25 0.33 ... ... The aim of the program is to read these values (several) of them, store to memory and do some sorts of interpolations. I created a structure, each holding the properties of the material at a given temperature. I then dynamically create an array of structures based on the number of data. If I had 100 readings, I create 100 arrays to structure. .h file

        struct Material {
        float temperature;
        float density;
        float viscosity;
        };

        typedef Material* MATERIAL;

        The above go into the header file .cpp file

        MATERIAL* g_ptrMaterial; //global variable

        void ReadFile (char* filePath)
        {
        vector<string> Tokens;
        int i = 0;
        string val;
        char c;

        ifstream file(filePath); //instantiate and open file
        
        if (!file.fail())
        {
        	//cout << "Enter to begin...";
        	//cin >> c;
        	//cout << "Reading from File ...";
        	g\_numberOfRows = getNumberOfRows(file); //gets number of readings
        	g\_ptrMaterial = new MATERIAL\[g\_numberOfRows\];
        
        	getline(file, g\_fileHeader); //remove column headers i.e. Temperature, Density, etc
        
        
        	while (getline(file, val))
        	{
        		g\_ptrMaterial\[i\] = (MATERIAL) malloc(sizeof(MATERIAL));
        		
        		Tokens = GetTokens(val);
        		
        		if (!Tokens.empty())
        		{
        			//convertToFloat: converts string type to float type
                                    g\_ptrMaterial\[i\]->temperature = convertToFloat(Tokens.at(0)); 	
        			g\_ptrMaterial\[i\]->density = convertToFloat(Tokens.at(1));
        			g\_ptrMaterial\[i\]->viscosity = convertToFloat(Tokens.at(2));
        
        			i++;
        		}
        	}
        }
        	
        else
        {
        	cerr << "FILE NOT FOUND!";
        	exit(1);
        }
        

        }

        //separates the input line into column readings
        vector<string > GetTokens (string val)
        {
        stringstream ss(val);
        string temp;
        vector<std::string > Tokens;

        while (ss >> temp)
        {
        	Tokens.push\_back(temp);
        }
        
        return Tokens;
        

        }

        Debugging What I di

        _ Offline
        _ Offline
        _Superman_
        wrote on last edited by
        #3

        Is your application multi-threaded? This problem can occur in such application due to some conflicts between threads. When you single step through code, the conflict may not occur.

        «_Superman_» I love work. It gives me something to do between weekends.
        Microsoft MVP (Visual C++)

        I 1 Reply Last reply
        0
        • _ _Superman_

          Is your application multi-threaded? This problem can occur in such application due to some conflicts between threads. When you single step through code, the conflict may not occur.

          «_Superman_» I love work. It gives me something to do between weekends.
          Microsoft MVP (Visual C++)

          I Offline
          I Offline
          Ibrahim Bello
          wrote on last edited by
          #4

          I didn't explicity create any extra threads, so I'll say it's single-threaded.

          1 Reply Last reply
          0
          • I Ibrahim Bello

            OK, actually this program works fine, but only when run from Visual Studio. However, when I click on the .exe or launch it from windows command prompt, I get an error: "Unhandled exception at 0x775e59c3 in Materials.exe: 0xC0000005: Access violation reading location 0x54a075d8" and Windows shuts the program down. The Requirement The program is to read from a text file a list of tabulated data of a given material: Temperature, Density, Viscosity... etc. For example: Temperature Density Viscosity ... ... 50 0.2 0.3 ... ... 100 0.25 0.33 ... ... The aim of the program is to read these values (several) of them, store to memory and do some sorts of interpolations. I created a structure, each holding the properties of the material at a given temperature. I then dynamically create an array of structures based on the number of data. If I had 100 readings, I create 100 arrays to structure. .h file

            struct Material {
            float temperature;
            float density;
            float viscosity;
            };

            typedef Material* MATERIAL;

            The above go into the header file .cpp file

            MATERIAL* g_ptrMaterial; //global variable

            void ReadFile (char* filePath)
            {
            vector<string> Tokens;
            int i = 0;
            string val;
            char c;

            ifstream file(filePath); //instantiate and open file
            
            if (!file.fail())
            {
            	//cout << "Enter to begin...";
            	//cin >> c;
            	//cout << "Reading from File ...";
            	g\_numberOfRows = getNumberOfRows(file); //gets number of readings
            	g\_ptrMaterial = new MATERIAL\[g\_numberOfRows\];
            
            	getline(file, g\_fileHeader); //remove column headers i.e. Temperature, Density, etc
            
            
            	while (getline(file, val))
            	{
            		g\_ptrMaterial\[i\] = (MATERIAL) malloc(sizeof(MATERIAL));
            		
            		Tokens = GetTokens(val);
            		
            		if (!Tokens.empty())
            		{
            			//convertToFloat: converts string type to float type
                                        g\_ptrMaterial\[i\]->temperature = convertToFloat(Tokens.at(0)); 	
            			g\_ptrMaterial\[i\]->density = convertToFloat(Tokens.at(1));
            			g\_ptrMaterial\[i\]->viscosity = convertToFloat(Tokens.at(2));
            
            			i++;
            		}
            	}
            }
            	
            else
            {
            	cerr << "FILE NOT FOUND!";
            	exit(1);
            }
            

            }

            //separates the input line into column readings
            vector<string > GetTokens (string val)
            {
            stringstream ss(val);
            string temp;
            vector<std::string > Tokens;

            while (ss >> temp)
            {
            	Tokens.push\_back(temp);
            }
            
            return Tokens;
            

            }

            Debugging What I di

            K Offline
            K Offline
            krmed
            wrote on last edited by
            #5

            Exactly what does filepath contain? When running from Visual Studio, the current directory is the one containing the .sln and .vcproj files. If your filepath only contains the name ("myfile.txt"), then it must exist in that directory. When you run outside of visual studio, the current directory is the one containing the .exe file (normally the debug or release directory) and the file would then have to exist in that folder. It's best to specify a full path name ("c:\\mydocs\\mydata\\myfile.txt") to avoid these problems. Hope that helps.

            Karl - WK5M PP-ASEL-IA (N43CS) PGP Key: 0xDB02E193 PGP Key Fingerprint: 8F06 5A2E 2735 892B 821C 871A 0411 94EA DB02 E193

            I D 2 Replies Last reply
            0
            • K krmed

              Exactly what does filepath contain? When running from Visual Studio, the current directory is the one containing the .sln and .vcproj files. If your filepath only contains the name ("myfile.txt"), then it must exist in that directory. When you run outside of visual studio, the current directory is the one containing the .exe file (normally the debug or release directory) and the file would then have to exist in that folder. It's best to specify a full path name ("c:\\mydocs\\mydata\\myfile.txt") to avoid these problems. Hope that helps.

              Karl - WK5M PP-ASEL-IA (N43CS) PGP Key: 0xDB02E193 PGP Key Fingerprint: 8F06 5A2E 2735 892B 821C 871A 0411 94EA DB02 E193

              I Offline
              I Offline
              Ibrahim Bello
              wrote on last edited by
              #6

              Thanks Karl. The filePath is the absolute path to the text file I'm accessing. Accessing the file doesn't seem to give issues both in debug and release. A section of the code checks for file failure:

              if(!file.fail())
              {
              //...
              }

              1 Reply Last reply
              0
              • K krmed

                Exactly what does filepath contain? When running from Visual Studio, the current directory is the one containing the .sln and .vcproj files. If your filepath only contains the name ("myfile.txt"), then it must exist in that directory. When you run outside of visual studio, the current directory is the one containing the .exe file (normally the debug or release directory) and the file would then have to exist in that folder. It's best to specify a full path name ("c:\\mydocs\\mydata\\myfile.txt") to avoid these problems. Hope that helps.

                Karl - WK5M PP-ASEL-IA (N43CS) PGP Key: 0xDB02E193 PGP Key Fingerprint: 8F06 5A2E 2735 892B 821C 871A 0411 94EA DB02 E193

                D Offline
                D Offline
                David Crow
                wrote on last edited by
                #7

                Good advice but I do not think that is the cause of the problem. If he was using file (the ifstream object) without first checking to see if it was valid (e.g., bad path), then an exception would be understandable.

                "Old age is like a bank account. You withdraw later in life what you have deposited along the way." - Unknown

                "Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

                I 1 Reply Last reply
                0
                • D David Crow

                  Good advice but I do not think that is the cause of the problem. If he was using file (the ifstream object) without first checking to see if it was valid (e.g., bad path), then an exception would be understandable.

                  "Old age is like a bank account. You withdraw later in life what you have deposited along the way." - Unknown

                  "Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

                  I Offline
                  I Offline
                  Ibrahim Bello
                  wrote on last edited by
                  #8

                  Problem solved and in 3 ways! 1. The "Keep it Simple Stupid" Advice works! Instead of creating an array of MATERIAL i.e Material*, I simply created an array of Material, and accessed each Material by the . notation rather than the ->. i.e.

                  g_ptrMaterials = new Material [g_numberOfRows];
                  Material mat;
                  mat.temperature = 200.00; // for example

                  2. One can stuff the structures into a vector:

                  vector vctr;
                  Material mat;
                  mat.temperature = 200.00; // for example
                  mat.density = bla bla;

                  vctr.push_back(mat);

                  3. Lastly I modified the initial code. I don't know why it works ...

                  MATERIAL* arrMaterial = new MATERIAL[g_numberOfRows];
                  g_ptrMaterial = &arrMaterial[0];

                  arrMaterial[i] = new Material; //everything works fine now

                  Perhaps the problem was mixing the malloc and new allocators? I suspected the problem was with the memory allocation, when the compiler continuously indicated errors in xmemory, dbgheap, and what not. It wasn't a v e r y pleasant experience. Anyway, I went for the first option, but one can go for any of the 3 options I suppose, without any harm. Thanks guys :)

                  1 Reply Last reply
                  0
                  Reply
                  • Reply as topic
                  Log in to reply
                  • Oldest to Newest
                  • Newest to Oldest
                  • Most Votes


                  • Login

                  • Don't have an account? Register

                  • Login or register to search.
                  • First post
                    Last post
                  0
                  • Categories
                  • Recent
                  • Tags
                  • Popular
                  • World
                  • Users
                  • Groups