how to get Program to read entire text file......


i currently have the program to process one word from the file, but i want it to read the entire text file, how would i do this.


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
char pw[20],name[500];

int a,b,x,y;



//prompt for password//

cout<<"\nPlease enter your password: ";

cin>>pw;

const char* filename="c:\\mytxtfile.txt";   //name of file
      ifstream infile(filename);
      if (!infile)
          cout<<"NO INPUT FILE!!!!"<<endl;

 
infile>>name;

x=strlen(name);

y=strlen(pw);
ofstream outfile;
outfile.open("c://encrypt.txt",ios::ate);
 

for(a=0,b=0; a<x; a++,b++){

if (b>=y)

b=0;

name[a]=name[a]+pw[b];

}


outfile<<endl<<name;

cout<<endl;
outfile.close();
cout<<"Encryption of your File has Finished!\n";

 

exit (0);

}
Why dont you just implement a while loop with end of file condition.

1
2
3
4
5
6
7
8
9
10
while(!infile.eof())
{
   infile>>name;

.
.
.

}
Do not loop on eof()!

If any error occurs, you will have an infinite loop.


The loop idea is correct. Ideally, your code should have a function that specifically encrypts a word. Something like:
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
string encrypt( const string& key, const string& s )
{
  string result;
  // Encrypt s into result here.
  ...
  return result;
}

int main()
{
  ifstream infile;
  ofstream outfile;
  // Open infile and outfile here.
  ...

  string key;
  // Get the user's "password" AKA encryption key here.
  ...

  // Encrypt each word in the input file
  // Write each encrypted word to the output file
  string word;
  while (infile >> word)
  {
    word = encrypt( key, word );
    outfile << word << endl;
  }

  // Check that we processed the input file ok
  if (!infile.eof())
  {
    cout << "Fooey! I failed to encrypt the entire input file.\n";
  }
  else
  {
    cout << "Encryption of your file has finished!\n";
  }

  infile.close();
  outfile.close();

  return 0;  // Please don't exit()...
}

Hope this helps.
1
2
3
4
5
6
7
string encrypt( const string& key, const string& s )
{
  string result;
  // Encrypt s into result here.
  ...
  return result;
}




I am confuse on that part. why encrypt s into result? dont i have to encrypt s into word . since word is the infile?
You need to hit the textbooks again. Read the chapters on functions and on variable scope and/or local variables.
Topic archived. No new replies allowed.