【问题标题】:Unable to reverse a string using reverse function in <algorithm> in C++ [closed]无法在 C++ 中使用 <algorithm> 中的反向函数来反转字符串 [关闭]
【发布时间】:2014-01-13 16:46:45
【问题描述】:

以下是我的代码: 我无法在文件算法中使用反向来反转字符串

#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

【问题讨论】:

  • endl,不是end
  • 问题出在上面那行的end。投票结束是一个由拼写错误引起的问题。
  • 这是一个很好的例子,说明为什么我不喜欢有 using 子句,所以我最终改用 std::endl
  • 或者,更好的是,'\n'。每行后刷新可能会减慢速度。
  • Aside:永远不要使用.eof().good() 作为循环条件。这样做通常会产生错误代码,就像这里一样。请改用while ( getline(fp, line) ) { ... }。见:stackoverflow.com/questions/5605125/…

标签: c++ string stl reverse


【解决方案1】:

正如 cmets 在声明中所说的那样

cout<<line<<end;

你写的是end而不是endl

但是我想说一下算法的反向。我在您的代码中看不到任何意义,因为每次变量行都被覆盖。所以你看不到反转的效果。可能会更好写

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

只需要包含标题&lt;iterator&gt;

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

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

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

【讨论】:

    【解决方案2】:

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

    cout<<line<<end;
    

    应该是

    cout<<line<<endl;
    

    【讨论】:

      猜你喜欢
      • 2013-02-25
      • 1970-01-01
      • 2014-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-30
      • 2023-03-28
      相关资源
      最近更新 更多