好吧所以这就是我所拥有但我得到一个错误说'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;
}
答案 0 :(得分:4)
在调用之前,您必须先将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);
答案 1 :(得分:2)
您需要将参数传递给方法吗?因为你的方法需要一个string
类型的参数,否则你需要重载它..它目前是失败的因为它正在寻找一个函数定义complexReverseString()
将您的代码更改为
complexReverseString(forward);
答案 2 :(得分:2)
在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;
答案 3 :(得分:2)
在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)