Open File, Print to a File/Console

okay, i usually create beg programs and they often compile. for some reason, this one is not compiling at all. i cant seem to figure out whats wrong.

my objective is to prompt user to open a file named "data.txt"
have HELLO WORLD printed in a scrambled version to a file named "secret.txt"
and also have it printed to the console screen.

but first and foremost, my bigger problem is not having the program compile properly. any have any suggestions?


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
 
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main()
{
  ifstream fin;
  fin.open("data.txt");
  if (!fin.good()) throw "I/O error";
  
  string fileName;
  cout << "What file do you want to use for input? ";
  getline(cin, fileName);
  fin.open(fileName.c_str());
  
  ofstream fout;
  fout.open("secret.txt", ios::app);
  if (!fin.good()) throw "I/O error";
  
  fout << " " << endl;
  fout.close();
  
  // encode string s by adding 1 to the ASCII code of each character
  string s = "Hello, World"; // an example
  for (int i = 0; i < s.length(); i++) // for each char in the string...
  s[i]++; // bump the ASCII code by 1

  
  while (true)
  {
    if (!fin.good()) break;
    
    string lineFromFile;
    getline(fin, lineFromFile);
    cout << lineFromFile << endl;
  } //  while
  
  fin.close();
  cin.ignore();
  cin.get();
  return 0;
}
Your close() file and open() file methods are in weird places, and what are the errors the compiler is giving you?

also here is a good start tutorial for file streams http://cplusplus.com/doc/tutorial/files/
Last edited on
What i think is you are opening an uncreated file for reading. Suppose "data.txt" exists
fin.open("data.txt");
this will open file.
In the next code segment:
string fileName;
cout << "What file do you want to use for input? ";
getline(cin, fileName);
fin.open(fileName.c_str());

if fileName does not exists then how can you open a file which does not exist.
In case of
fout.open("secret.txt", ios::app);
if file doesn't exist a new one will be created.

Based on my understanding of what you want here is the sample code.
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main()
{
ifstream fin;
string fileName;
ofstream fout;
fout.open("secret.txt",ios::out);
// encode string s by adding 1 to the ASCII code of each character
string s = "Hello, World"; // an example
for (int i = 0; i < s.length(); i++) // for each char in the string...
s[i]++; // bump the ASCII code by 1
fout.write(s.c_str(),sizeof(s));
fout.close();
fin.open("secret.txt",ios::in);
string line;
while (getline(fin, line))
{
string lineFromFile;
cout << line << endl;
if (!fin.good()) break;


} // while

fin.close();
return 0;
}

So you better read http://cplusplus.com/doc/tutorial/files/



Topic archived. No new replies allowed.