How to read text file

Pages: 12
I am having trouble understand how to read a file and then print it out. Below the code is suppose to write name and grade to a text file and then read the text file and display. I can write to the text file, but i'm not understand how to read from it cause it is not working at all.[b].Please ignore the code that is commented out..[/b] the text file is suppose to be called grade...enter a 0 to input data..enter -1 to stop input.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
  #include <iostream>
#include <fstream>

using namespace std;

int main()
{
    char filename[256];
    int inputValue;
    char Trash[2];
    int i = 0;
    double sum = 0.0;
   double Averange =0;
   int count =0;
   	int n=0;
   int number;
 
   
      


    cout<<"Enter file name: ";
    cin.getline(filename, 256);

    ofstream filegrade(filename);
     if(filegrade.is_open())
    {
        /* cout<<"Enter name : ";
         cin.getline(inputValue, 256);
         fileWrite<<inputValue<<endl;*/
         
         
        while(i != -1)
        {   cout<<"Enter a name (-1 to end or 0 to continue):";
            cin>>i;
            cin.getline(Trash,2);
            
            
            if(i == 0)
            {
                cout<<"Enter name: ";
                cin.getline(filename, 256);
                filegrade<<filename<<endl;
               // inputValue [256] = NULL;
               
                 cout<<"Enter grade : ";
         		cin>>(inputValue);
                filegrade<<inputValue<<endl;
                
               // inputValue [256] = NULL;
               count++;
               sum = sum + inputValue;

            } //break;
        } 
    }
    else
        cout<<"can not open a file"<<endl;
        
        

  

   if(filegrade.is_open())
    {
        while(1)
		filegrade.open("grade.txt");
		filegrade>>number;
		if(readFile.eof())
              

	/*	filegrade <<"Hello... \n";
		cout<<"grade"<<number<<"\n";
                  
   			//filegrade
			   cout<<"\nSum: "<<sum<<endl;
    	//	filegrade 
    	
    	
			cout<<"\nClass Average: "<<sum/count<<endl;*/
       
    }  break;
filegrade.close();

        
           // cout<<"\nSum: "<<sum<<endl;
    	//	cout<<"\nAverage: "<<sum/count<<endl;

        
        
  
    return 0;
}
What do you mean by "it is not working at all"? Does it make the bears in your area angry at you? Does it install Internet Explorer with a virus? Does it cause your neighbor's house to implode? You need to be specific.
it doesn't read.. file.. like I said i can write..but can't figure out how to write the code to read file..the file name is grade.
ok so i change the last part of the code to this to read txt file.. the program will run.. but once it gets to the read portion..it stops and exit program and says process exited with return value 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38


	ifstream getgrade(filename);
   if(filegrade.is_open())
    {
        while(1){
        
		getgrade.open("grade.txt");
		getgrade>>number;
		if(getgrade.eof());
		
		
		cout<<"grade"<<number<<"\n";
		break;
      }

		filegrade <<"Hello... \n";
		cout<<"grade"<<number<<"\n";
                  
   			//filegrade
			   cout<<"\nSum: "<<sum<<endl;
    	//	filegrade 
    	
    	
		//	cout<<"\nClass Average: "<<sum/count<<endl;*/
       
    }  
getgrade.close();

        
           // cout<<"\nSum: "<<sum<<endl;
    	//	cout<<"\nAverage: "<<sum/count<<endl;

        
        
  
    return 0;
}
Put an opening curly brace { on line 24 and a closing curly brace } on line 59. Otherwise the file is still open for output when you try to open it for input.
ok I made those changes.. again the program will write to txt file but i cant get it to read it.. here is my new adjusted code.. still doesnt work right

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    char filename[256];
    int inputValue;
    char Trash[2];
    int i = 0;
    double sum = 0.0;
   double Averange =0;
   int count =0;
   	int n=0;
   int number;
 
   
      


    cout<<"Enter file name: ";
    cin.getline(filename, 256);
{

    ofstream filegrade(filename);
     if(filegrade.is_open())
    {
        /* cout<<"Enter name : ";
         cin.getline(inputValue, 256);
         fileWrite<<inputValue<<endl;*/
         
         
        while(i != -1)
        {   cout<<"Enter a name (-1 to end or 0 to continue):";
            cin>>i;
            cin.getline(Trash,2);
            
            
            if(i == 0)
            {
                cout<<"Enter name: ";
                cin.getline(filename, 256);
                filegrade<<filename<<endl;
               // inputValue [256] = NULL;
               
                 cout<<"Enter grade : ";
         		cin>>(inputValue);
                filegrade<<inputValue<<endl;
                
               // inputValue [256] = NULL;
               count++;
               sum = sum + inputValue;

            } //break;
        } filegrade.close();
    }
    else;
      cout<<"can not open a file"<<endl;
}      
        
        

  
	ifstream getgrade(filename);
   if(getgrade.is_open())
    {
        while(1){
        
		getgrade.open("grade.txt");
		getgrade>>number;
		
		cout<<"grade"<<number<<"\n";
		
		if(getgrade.eof());
		
		
		
		break;
      }

		//filegrade <<"Hello... \n";
		cout<<"grade"<<number<<"\n";
                  
   			//filegrade
			   cout<<"\nSum: "<<sum<<endl;
    	//	filegrade 
    	
    	
		//	cout<<"\nClass Average: "<<sum/count<<endl;*/
       
    }  
getgrade.close();

        
           // cout<<"\nSum: "<<sum<<endl;
    	//	cout<<"\nAverage: "<<sum/count<<endl;

        
        
  
    return 0;
}


this is what I get when i run the program... notice the read portion of the program is not showing..

Enter file name: grade
Enter a name (-1 to end or 0 to continue):0
Enter name: test1
Enter grade : 88
Enter a name (-1 to end or 0 to continue):-1
can not open a file

--------------------------------
Process exited with return value 0
Press any key to continue . . .
What is line 71 for? You already opened the file on line 66.
all the example i see have ifstream..stream name..and then

streamname.open.. even the powerpoints from my class..

i change the code to this..and its working better. it seems to be reading the file now.. only problem is the output looks like its showing the address not the value...

1
2
3
4
5
6
7
8
9
10
11
12
13


	ifstream getgrade(filename);
	getgrade.open("grade.txt");
   if(getgrade.is_open())
    {
        while(1){
        getgrade>>number;
		if(getgrade.eof());
		break;
		
		cout<<"grade"<<number<<"\n";
      }
Not sure how to fix that..
I just noticed that you're changing the filename when you write to the file, that's definitely a problem.
the file name is grade..I never changed that..
Look at lines 24, 27, 44, and 66.
Ok..right now your just confusing me.. Can you write a simple code that shows you writing to a file that doesn't already exist and then reading from that text file. and please make sure there is both char and numbers written to and read from the text file.

I'm not asking you to do my work above..I just need to see an example..because right now I am totally confused and your question are not helping me at all..

Thank you.l
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <string>
#include <fstream>

int main()
{
    {
        std::ofstream out ("data.txt"); //file is created if it doesn't exist
        for(unsigned i = 0; i < 10; ++i)
        {
            std::cout << "Enter description for #" << i << ": " << std::flush;
            std::string desc;
            std::getline(std::cin, desc);
            if(!desc.empty()) //allows you to skip some numbers, just an example
            {
                out << i << " " << desc << std::endl;
            }
        }
    }
    std::cout << std::endl << std::endl;
    {
        std::ifstream in ("data.txt");
        unsigned id;
        std::string desc;
        while(std::getline((in >> id).ignore(1), desc)) //this may look confusing
        {
            std::cout << "#" << id << " = \"" << desc << "\"" << std::endl;
        }
    }
}
The while loop in the second half of the code may seem confusing, but all it does is read into id, then ignore the space after it, and then read in the description to the next newline. The reason for it being in the loop condition is so that if any input operation fails (such as trying to read at the end of the file), the loop will end.
Last edited on
Ok that was kind of above my head now..I am a beginner..this is example of code we used in class to read text.. can you help me using this technique to read the data from text in my program..here is the code they gave us as example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    double number, sum = 0.0;
    int count = 0;

    ifstream readFile;
    readFile.open("read.txt");

  if(readFile.is_open())
    {
        while(true)
        {
            readFile >> number;
            if(readFile.eof())
                break;
            sum += number;
            cout<<"number is: "<<number<<"\n";
            count++;
        }

    }
   else
        cout<<"can not open a file"<<endl;

    readFile.close();

    cout<<"\nSum: "<<sum<<endl;
    cout<<"\nAverage: "<<sum/count<<endl;
    return 0;
}



Try this, Let me know if it helps.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include<cstdlib>
#include <string>
#include<fstream>
using namespace std;
int main()
{
    ifstream infile("C:\\Users\\Diablo\\Desktop\\read.txt"); // give your filename here

    string s;

    if(!infile.is_open())
    {
        cout << "Error:No file found.\n";
        cout << "Program terminating.\n";
        exit(EXIT_FAILURE);
    }

    while(infile >> s)
    {
        cout << s << "\n";

    }
    return 0;
}
Ok so I applied your example..here is my code changes ..However now it runs but again it does not seem to do the read portion, or at least does not display result..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

 ifstream outgrade(filename);
       //  filegrade.open(filename);
	   
  		 if(outgrade.is_open())
		   {
  		 	
       cout << "Error:No file found.\n";
        cout << "Program terminating.\n";
      
        exit(EXIT_FAILURE);
  		 	
  		 }
  		 

        while(outgrade >> number){

        //getline(filegrade, imputValue);

		if(outgrade.eof());
		break;
		
		cout<<"grade"<<number<<"\n";
		//<<"grade"<<number<<"\n";
      }


Output

Enter file name: grade
Enter a name (-1 to end or 0 to continue):0
Enter name: test1
Enter grade : 95
Enter a name (-1 to end or 0 to continue):-1

--------------------------------
Process exited with return value 0
Press any key to continue . . .
what is the type of the variable (number)?
and you don't have to check for eof condition again.
Last edited on
Here is the complete code. Try it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include<iostream>
#include<fstream>
#include<string>
#include<cstdlib>

using namespace std;

int main()
{
    ofstream outFile("create.txt");
    char automobile[50];
    int year;
    double a_price;
    double d_price;

    cout << "Enter the make and model of automobile: ";
    cin.getline(automobile, 50);
    cout << "Enter the model year: ";
    cin >> year;
    cout << "Enter the original asking price: ";
    cin >> a_price;
    d_price = 0.913 * a_price;


    outFile << "Make and model: " << automobile << endl;
    outFile << "Year: " << year << endl;
    outFile << "Was asking $" << a_price << endl;
    outFile << "Now asking $" << d_price << endl;

    outFile.close();


    ifstream infile("create.txt");

    if(!infile.is_open())
    {
        cout << "Not open.";
        exit(EXIT_FAILURE);
    }
    string data;

    while(infile >> data)
    {
        cout << data ;
        cout << "\n";
    }

    return 0;
}
Pages: 12