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'."
#include <iostream>
#include <fstream>
#include <iomanip>
#include <stdlib.h>
usingnamespace std;
int main()
{
string line;
char letter;
constchar 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.