Homework Problem: ofstreams and ifstreams

Hello,

I have an assignment due tonight that needs to at least function. The assignment is to create a txt file and write a sentence in it. From there, the program needs to display this sentence from the file and then find how many of a letter is used (basically an array). An example would be "There is a green car in the driveway." So if I put the letter 'g' in the query, the program would say "There is 1 'g'."

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
#include <iostream>
#include <fstream>
#include <iomanip>
#include <stdlib.h>
using namespace std;

int main()
{
    string line;
	char letter;
	const char arraySize=10;
	char n[10];

	ofstream Documents( "Text1.txt", ios::out );
	  if (!Documents)
	  {
		 cout << "File could not be opened\n";
		 return 0;
	  }
        if (Documents.is_open())
        {
           Documents<< "The quick brown fox jumped over the lazy dog's back";
        }
    ifstream Documents("Text1.txt");

            while ( getline (Documents,line)
               {
                   cout << line << endl;
                   cout << endl;
                   cout << "Please enter a lower-case letter: ";
                   cin >> letter;
               }
                for ( int n=0; line[ i ]!='\0'; i++)
                {
                    cout <<letter<<'*';
                }
                cout << endl;
        Documents.close();
	  return 0;
}


The main issue I'm having is trying to get a program to both create a file, write something in it, then read its contents. I looked at the tutorials on the main page but they are not as clear cut as I hoped they were.
Line 24, you declare an ifstream with the same name as an existing variable. If you use a different name it could possibly work. Remember to close the file before trying to open the same file for 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
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ofstream outDocuments("Text1.txt");
    if (!outDocuments)
    {
        cout << "File could not be opened\n";
        return 1;
    }

    outDocuments << "The quick brown fox\njumped over the\nlazy dog's back";
    outDocuments.close();
        
    ifstream inDocuments("Text1.txt");
    string line;
    while ( getline (inDocuments,line) )
    {
        cout << line << endl;
    }
   
}

Last edited on
Thanks! That worked wonders. But I had to drop string line; in order for it to work. Now I have to figure arrays out, again.
Topic archived. No new replies allowed.