反向字符串无循环

reverse string no loops

本文关键字:循环 字符串      更新时间:2023-10-16

好的,这就是我所拥有的,但我收到一个错误说"complexReverseString":找不到标识符???我在哪里出错了,我检查了一下无济于事

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
    ifstream input;
    string forward;
    cout << "Please enter a string to see its reverse. (Will display reverse twice)" << endl;
    input.open("information.txt");
    cin >> forward;
    //reverseString(forward, findStringSize(forward)); a function I'm not actually calling
    input >> forward;
    complexReverseString();
    input.close();

}
int complexReverseString(string userInput)
{
    string source(userInput);
    string target( source.rbegin(), source.rend() );
    cout << "The reversed string is " << target << endl;
    return 0;
}

调用它之前,您必须先对complexReverseString()进行原型设计。

在源文件中的main入口点之前执行此操作,如下所示:

int complexReverseString(string userInput);
int main() { ... }

或者在单独的标头中执行此操作:

#ifndef COMPLEX_STR_HPP
#define COMPLEX_STR_HPP
int complexReverseString(string userInput);
#endif /* COMPLEX_STR_HPP */
/* int main.cpp */
#include "complex_str.hpp"
int main() { ... }

其次,您忘记将参数传递给函数:

 complexReverseString( /* parameter here */ );
 e.g
 complexReverseString(forward);

第三,由于您没有更改complexReverseString()中的字符串,因此我建议使用const字符串,也许是对字符串的引用:

int complexReverseString(const string& userInput);

你需要将参数传递给方法吗?因为你的方法需要一个类型的参数string否则你需要重载它。它目前失败了,因为它正在寻找一个函数定义complexReverseString()

将代码更改为

complexReverseString(forward);

在 C++ 中反转字符串或任何其他没有显式循环的容器的最简单方法是使用反向迭代器:

string input;
cin >> input;
// Here is the "magic" line:
// the pair of iterators rbegin/rend represent a reversed string
string output(input.rbegin(), input.rend());
cout << output << endl;

在 C/C++ 中,编译器从上到下读取源代码。如果在编译器读取方法之前使用它(例如,当该方法在底部定义,并且您在main()中使用它并且main()位于顶部时),编译器将不会运行项目/文件夹中的所有源/头文件,直到找到该方法或遍历所有文件。

您需要做的是对您的方法进行原型设计,或者在顶部定义它。

函数原型基本上是一个方法标头,用于通知编译器该方法将在源代码中的其他地方找到。

原型:

#include <iostream>    
#include <fstream>    
#include <string>
using namespace std;
// DEFINE PROTOTYPES BEFORE IT'S CALLED (before main())
int complexReverseString(string);
int main()    
{    
    // your main code
}    
int complexReverseString(string userInput)    
{    
    // your reverse string code
}

原型设计将允许您更轻松地查看方法和方法标头。

或者在顶部定义compledReverseString()

#include <iostream>    
#include <fstream>    
#include <string>
using namespace std;
// DEFINE METHOD BEFORE IT'S CALLED (before main())
int complexReverseString(string userInput)    
{    
    // your reverse string code
}
int main()    
{    
    // your main code
}

这些样式中的任何一种都会产生相同的结果,因此由您决定要使用哪一种。

除此之外,当您在main中调用complexReverseString()时,您忘记传递其参数,该参数应该是forward。所以不是complexReverseString(),而是complexReverseString(forward)