Function to reverse string output as read from text file

So here's my function, but no matter how I reference it in another function to output this plus plus other output (mainly the line forward, the line backwards (my problem), and counting the number of vowels found in a line of text (which I got working) ). From a function standpoint, am I at least on the right track. Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void rstring(ifstream& read)

{

	string line;
    string::reverse_iterator reverse;

	while (!read.eof())
          read.get();
          for ( reverse=line.rbegin() ; reverse < line.rend(); reverse++ )
             cout << *reverse;   
		  line = read.peek();      
       cout << endl << endl; 
	   display(*reverse);
      
}

So what is it meant to do? By the way, reverse isn't a pointer... I don't think the reference operator needs to be there... Try removing it.
It's an iterator, so you do need the * there. Anyway, I'm not really understanding what your question is. Is it not outputting correctly, or giving you errors?
He is trying to iterate over and empty line.

You are better off just reading the line in its entirety, then reversing it.
1
2
3
4
5
#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
1
2
3
4
5
6
7
8
9
void rstring( istream& ins )
  {
  string line;
  while (getline( ins, line ))
    {
    reverse( line.begin(), line.end() );
    display( line );
    }
  }

A few other things:

1. The peek() function only returns the next character. It does not advance the stream.

2. Better to just parameterize on an istream unless your function requires an ifstream.

3. Don't forget your opening and closing braces. As you have it, lines 8 and 9 are the while loop. Everything following is not. Indentation is important only for use humans in C and C++.

4. Don't loop on istream::eof(). If there is an error in reading, you'll loop forever. Instead, code against istream::good(), as I did above. (The getline() function returns the stream, which implicitly tests good().)

5. Hmm... had to step away for a moment and I can't remember what I was going to write here. Something mildly helpful, I think...

Anyway, hope this helps.

[edit]
Oh, also, the display() function should take a const string& as argument.
Last edited on
Topic archived. No new replies allowed.