无法使用C ++ </algorithm>中<algorithm>中的反向函数反转字符串

时间:2014-01-13 16:46:46

标签: c++ string stl reverse

以下是我的代码: 我无法使用文件算法中的反向

来反转字符串
#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());    
} 

}

我得到的编译错误是:

file.cpp: In function ‘int main()’:
file.cpp:21:15: error: ‘end’ was not declared in this scope

2 个答案:

答案 0 :(得分:1)

正如声明中的评论中已经说过的那样

cout<<line<<end;

你写了end而不是endl

但是我想说的是反向算法。我的代码中没有任何意义,因为每次都会覆盖变量行。所以你没有看到倒车的效果。也许最好写一下

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

只需要包含标题<iterator>

此外,您可以在不显式使用算法反向的情况下反转std :: string类型的对象。例如

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

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

答案 1 :(得分:1)

您的字符串反向逻辑正在运行。问题是拼写错误:D

cout<<line<<end;

应该是

cout<<line<<endl;