Thread: text files in c++

  1. #1
    Registered User
    Join Date
    Mar 2006
    Posts
    2

    text files in c++

    i can read text files in c++, but how can i use the information

    that is actually in the text files, which is just integers

    and do calculations with them, ie find the mean.

    i am finding it very difficult to find the solution to this, and to

    acutally use the integers within the text file and use them for

    calculations.

    Any help will be greatly appreciated.

    thanks


    DungeonMaster

  2. #2
    C / C++
    Join Date
    Jan 2006
    Location
    The Netherlands
    Posts
    312
    use ifstream:

    Code:
    ifstream load("save.txt");
      
      if(!load.is_open())
      {
        cout << "No saves yet..." << endl;
      }
      
      load >> int 1;
      load >> int 2;
      load >> int 3;
      // etc...
    
      file.close();
    To create a file and put info in it, use ofstream:

    Code:
    ofstream file("save.txt");
      file << int 1 << " " << int 2 << " " << int 3 << endl;
      file.close();
    Maybe not the best way to do it, but it works fine on my compiler.
    Operating Systems:
    - Ubuntu 9.04
    - XP

    Compiler: gcc

  3. #3
    Registered User
    Join Date
    Mar 2006
    Posts
    2
    this is what i have of my code so far:
    i've also included attachments of some of the txt files i am using
    i would just like to know how i could use the integer values within the text files and actually get the mean values for them etc..

    very very greatful for any help
    Code:
    #include <fstream>
    #include <string>
    #include <iostream>
    #include <iomanip>
    #include <cmath>
    #include <cstdlib>
    using namespace std;
    
    int main()
    {    int c;                                                           // open
        string str[20];                        // string array
        int i = 0, j = 0, last;                // counter variables
        ifstream myFile("figures1.txt");       // input file object
        if (! myFile)
        {                                                           // open
              cout << "Unable to open input file" << endl;
              return -1;
              }                                                     // close
              while (! myFile.eof())           // loop through data
              {                                                    // open
                    if ((i+1) % 2 ==0) getline(myFile, str[i++]);
                    else getline(myFile, str[i++], '\t');
                    }                                              // close
                    last = i;                  // last element #
                    i = 0;
                    while (i < last)           // display records
                    {                                             // open
                          cout << "Choice Number:\t" << str[i++] << endl;
                          cout << "Company Name:\t"        << str[i++] << endl;
                         
                          }    myFile.close();                                   // close
                                        // close the file
                          cin >> c;
    
    					  switch (c){
    
    case 1: cout<< "you have selected company, Diago Plc\n"<< endl;
     
    	{
    	string str;
    	ifstream myFile("Diago plc.txt");
    	if (!myFile)					// Always test file open
    	{
    		cout << "Error opening output file" << endl;
    		return -1;
    	}
    	while (! myFile.eof()) // Loop through lines
    	{
    		getline(myFile, str);
    		cout << str << endl;
    	}
    	myFile.close();
    	
    }
    	   break;
    case 2: cout<< "you have selected company, Sabmiller Plc\n"<<endl;
    	{
    	string str;
    	ifstream myFile("sabmiller plc.txt");
    	if (!myFile)					// Always test file open
    	{
    		cout << "Error opening output file" << endl;
    		return -1;
    	}
    	while (! myFile.eof()) // Loop through lines
    	{
    		getline(myFile, str);
    		cout << str << endl;
    	}
    	myFile.close();
    	
    }
    	break;
    case 3: cout<< "you have selected company, Associated British Foods Plc\n"<<endl;
    {
    	string str;
    	ifstream myFile("associated british foods plc.txt");
    	if (!myFile)					// Always test file open
    	{
    		cout << "Error opening output file" << endl;
    		return -1;
    	}
    	while (! myFile.eof()) // Loop through lines
    	{
    		getline(myFile, str);
    		cout << str << endl;
    	}
    	myFile.close();
    	
    }
    	break;
    case 4: cout<< "you have selected company, Scottish and Newcastle Plc\n"<<endl;
    	{
    	string str;
    	ifstream myFile("scottish and newcastle.txt");
    	if (!myFile)					// Always test file open
    	{
    		cout << "Error opening output file" << endl;
    		return -1;
    	}
    	while (! myFile.eof()) // Loop through lines
    	{
    		getline(myFile, str);
    		cout << str << endl;
    	}
    	myFile.close();
    	
    }
    	break;
    case 5: cout<< "you have selected company, Tate and Lyle Plc\n"<<endl;
    	{
    	string str;
    	ifstream myFile("tate and lyle.txt");
    	if (!myFile)					// Always test file open
    	{
    		cout << "Error opening output file" << endl;
    		return -1;
    	}
    	while (! myFile.eof()) // Loop through lines
    	{
    		getline(myFile, str);
    		cout << str << endl;
    	}
    	myFile.close();
    	
    }
    	break;
    case 6: cout<< "you have selected company, Kerry Group Plc\n"<<endl;
    	{
    	string str;
    	ifstream myFile("kerry group.txt");
    	if (!myFile)					// Always test file open
    	{
    		cout << "Error opening output file" << endl;
    		return -1;
    	}
    	while (! myFile.eof()) // Loop through lines
    	{
    		getline(myFile, str);
    		cout << str << endl;
    	}
    	myFile.close();
    	
    }
    	break;
    default: cout << "you have not entered a valid choice"<<endl;
    cout<<" please re-enter your choice"<<endl;
    					  }
    return 0;
                          }

  4. #4
    ♥Sexy Coding Hunk♥ CartoonLarry's Avatar
    Join Date
    Dec 2003
    Location
    Michigan
    Posts
    50
    i would just like to know how i could use the integer values within the text files and actually get the mean values for them etc..
    I would copy the contents into a stl map.

    figures1-1.txt

    1 Diago Plc
    2 Sabmiller Plc
    3 Associated British Foods Plc
    4 Scottish and Newcastle Plc
    5 Tate and Lyle Plc
    6 Kerry Group Plc

    map<int, const char *> figures;

    //Use getline in a loop to retrieve text and then separate the number from the value.

    figures[numKeyVariable] = strValueVariable; // put values into map using this method.

    // Or you could insert the values
    figures.insert(pair<int, const char *>(numKeyVariable, strValueVariable));

    map<int, const char *>::iterator figure = figures.find(1); // Find value at key 1
    figure->second; // would hold the value "Diago Plc"

    figure = figures.find(5); // Find value at key 5
    figure->second; // would hold the value "Tate and Lyle Plc"

    Hope this helps
    Last edited by CartoonLarry; 03-14-2006 at 02:25 PM.

  5. #5
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    General Items:

    1. Need to work of the formating of that code a bit.
    2.
    Code:
    while (! myFile.eof()) // Loop through lines
    {
        getline(myFile, str);
        cout << str << endl;
    }
    It is generally a bad idea to use eof to control a loop like this. The problem is that the eof flag does not get set until after a read attempt is made. Consider a file with a single line of data "Hello World". You code will read that text into str and eof will still be false even though you are effectively at the end, i.e. no more to read. So, you back around again and test eof which is false so the loop body executes once more and you try to read from the file (eof gets set to true now). Since there is nothing to read, no data gets loaded into str which retains its value from the previous iteration of the loop. Since eof is now true we don't go back through the code in the loop body a third time. The end result is you would see "Hello World" printed twice.

    The solution to this is easy; modify the code by placing the call to getline in place of the eof test.

    Code:
    while( getline(myFile, str) ) // Loop through lines
    {
        cout << str << endl;
    }
    This works because the getline call returns the stream, myFile in this case, which when used in this type of context checks the state of the stream in question to see if there are any errors (like eof being set). End result here is that you only would see "Hello World" once like you should.

    3.
    Code:
    case 1: cout<< "you have selected company, Diago Plc\n"<< endl;
            {
                ifstream myFile("Diago plc.txt");
    
                ...
    
                myFile.close();
            }
    The close call is generally not required since by the time you reach the }, the destructor will be called for the myFile ifstream object which calls close all by itself if necessary. It isn't hurting anything by having it there, but it isn't needed. Also, you have an another ifstream object called myFile in scope here which can be confusing even though the compiler shouldn't have any trouble telling them apart, consider calling them something different (just a suggestion).
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  6. #6
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    It is generally a bad idea to use eof to control a loop like this. The problem is that the eof flag does not get set until after a read attempt is made.
    In addition, a stream error can occur while you are reading from the file, which will prevent you from reading any more data from the file. You won't be at eof, so the while loop will enter into an infinite loop--attempting to read from the file, failing because of the stream error, and continuing with the loop since you aren't at eof.
    Quote Originally Posted by hk_mp5kpdw
    The solution to this is easy; modify the code by placing the call to getline in place of the eof test.
    Code:
    while( getline(myFile, str) ) // Loop through lines
    Last edited by 7stud; 03-14-2006 at 03:50 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. added start menu crashes game
    By avgprogamerjoe in forum Game Programming
    Replies: 6
    Last Post: 08-29-2007, 01:30 PM
  2. Reading text files?
    By Kate in forum C Programming
    Replies: 3
    Last Post: 06-30-2006, 01:22 AM
  3. A bunch of Linker Errors...
    By Junior89 in forum Windows Programming
    Replies: 4
    Last Post: 01-06-2006, 02:59 PM
  4. reading certain parts of text files
    By Captain Penguin in forum C++ Programming
    Replies: 2
    Last Post: 10-10-2002, 09:45 AM
  5. Outputting String arrays in windows
    By Xterria in forum Game Programming
    Replies: 11
    Last Post: 11-13-2001, 07:35 PM