Using getline to read a line

The following is a personal program I'm working on to make it easy to put pictures from my facebook to my personal website. All it currently does is open a file in which I have all my image addresses, then it saves it to a new file where it is in HTML format. Its been a year since I was in C++ so I dont remember too much. This is what I have so far.

MY ERROR is in the getline function. Im not sure how to use it. I want it to take the first line. Then loop to the second and so on. Then end when it gets to the end of the file.

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
// basic file operations
#include <iostream>
#include <fstream>
using namespace std;

  ifstream in;
  ofstream out;
  int i=1;
  char title;
  char fin[100], fout[100];
  char PicURL[100];
  
int main () {
  
  cout << "Enter input file name : ";
  cin >> fin;
  in.open(fin);
  cout << "Enter output file name : ";
  cin >> fout;
  out.open(fout);
  
  while (!in.eof()){
  in.getline(PicURL,50);
  out << "<a href=\""<< PicURL <<"\" rel=\"lightbox[Bike]\"title=\"Blank\"><img src=\""<< PicURL <<"\" alt=\"Blank\" width=\"170\" height=\"130\" /></a>\n";
 }

  out.close();
  in.close();
  return 0;
}


Thanks...
Because EOF occurs after you attempt to read past it, meaning it is signalled between lines 23 and 24. Don't loop on EOF. Instead, use:

22
23
24
  while (in.getline(PicURL,50)) {
    out << ...
  }

You'd make it even better if you change your strings to std::string:

10
11
  string fin, fout;
  string PicURL;
 
  in.open(fin.c_str());
22
23
24
  while (getline(in,PicURL)) {
    out << ...
  }

Hope this helps.

[edit] Fixed an error and added how to open the file using a std::string
Last edited on
Thanks for the help but, it's still not working exactly. I changed the code to String and it wouldnt compile. Then I changed it back with the new while loop and it compiled. When it runs though. There is no text in the out file.

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

  ifstream in;
  ofstream out;
  int i=1;
  char title;
  char fin[100], fout[100];
  char PicURL[100];
  
  
int main () {
  cout << "Enter input file name : ";
  cin >> fin;
  in.open(fin);
  cout << "Enter output file name : ";
  cin >> fout;
  out.open(fout);
  
  while (in.getline(PicURL,50)) {
  out << "<a href=\""<< PicURL <<"\" rel=\"lightbox[Bike]\"title=\"Blank\"><img src=\""<< PicURL <<"\" alt=\"Blank\" width=\"170\" height=\"130\" /></a>\n";
 }

  out.close();
  in.close();
  return 0;
}
*BUMP*
Do your filenames have any spaces in them?
Does your input file have data?
I FIGURE IT OUT!! lol, after a couple hours of being an idiot. I realized that I wasn't taking into consideration that the console has to read the file name plus .txt :) THANKS DUOAS!
Topic archived. No new replies allowed.