-2

Following is my code: I am unable to reverse the string using reverse in file algorithm

#include<iostream>
#include<fstream>
#include<string>
#include<algorithm>
#include<iterator>

using namespace std;
int main()
{ 
 ifstream fp;
 string line;
 fp.open("list");
 if(!fp.is_open())
 {
  cerr<<"file not open";
 }

 while(!fp.eof())
{
  getline(fp,line);
  cout<<line<<end;
  std::reverse(line.begin(),line.end());    
} 

}

Compilation error I get is:

file.cpp: In function ‘int main()’:
file.cpp:21:15: error: ‘end’ was not declared in this scope
priyanka
  • 144
  • 2
  • 14
  • 4
    It is `endl`, not `end`. – Nawaz Jan 13 '14 at 16:47
  • It's the `end` on the line above that is the problem. Voting to close as a question caused by a typo. – Sergey Kalinichenko Jan 13 '14 at 16:50
  • 1
    This is a good example of why I like to not have a `using` clause so I end up with `std::endl` instead. – Sean Perry Jan 13 '14 at 16:50
  • Or, better still, `'\n'`. Flushing after every line might slow things down somewhat. – Mike Seymour Jan 13 '14 at 16:50
  • If you think you have a problem reversing a string, then test that with a valid string first. Mixing in IO only confuses the matter. – juanchopanza Jan 13 '14 at 16:51
  • 3
    *Aside*: Never use `.eof()` or `.good()` as a loop condition. Doing so will usually produce buggy code, as it does here. Try `while ( getline(fp, line) ) { ... }` instead. See: http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – Robᵩ Jan 13 '14 at 16:58

2 Answers2

1

As it already was said in comments in statement

cout<<line<<end;

you wrote end instead of endl

However I would like to say about the algorithm reverse. I do not see a sense in your code because each time variable line is being overwritten. So you do not see the effect of the reversing. Maybe it would be better to write

while( getline( fp, line ) )
{
  cout << line << endl;
  std::reverse_copy( line.begin(), line.end(), ostream_iterator<string>( cout, "\n" ) );    
}

Only you need to include header <iterator>

Also you can reverse an object of type std::string without explicitly using algorithm reverse. For example

cout << line << endl;
line.assign( line.rbegin(), line.rend() );
cout << line << endl;

or

cout << line << endl;
cout << string( line.rbegin(), line.rend() )  << endl;
Vlad from Moscow
  • 224,104
  • 15
  • 141
  • 268
1

Your string reverse logic is working. The problem is typo :D

cout<<line<<end;

should be

cout<<line<<endl;
Digital_Reality
  • 3,805
  • 1
  • 19
  • 28