我正在编写一个程序来使用堆栈来反转字符串。我的代码中出现了2个错误。 1.没有运营商>>匹配操作数2.在反向行(字符串);它错误说(字符串)类型名称是不允许的。知道为什么吗?
#include <iostream>
#include <string.h>
#include <stack>
using namespace std;
void Reverse(char);
int main()
{
char object;
cout << "Please enter a line of text.\n";
cin >> object;
char * point = new char[object.length() + 1];
strcpy(point, object.c_str());
Reverse(point);
Reverse(point);
printf(" %s", object);
system("pause");
return 0;
}
void Reverse(char *p)
{
stack<char> S;
for (int i = 0; i<strlen(p); i++)
S.push(p[i]);
for (int i = 0; i<strlen(p); i++)
{
p[i] = S.top();
S.pop();
}
}
更新的代码:cin&gt;&gt;上的错误object表示初始问题没有运算符匹配操作数
#include <iostream>
#include <string.h>
#include <stack>
using namespace std;
void Reverse(string);
int main()
{
string object;
cout << "Please enter a line of text.\n";
cin >> object;
char * point = new char[object.length() + 1];
strcpy(point, object.c_str());
Reverse(point);
printf(" %s", point);
system("pause");
return 0;
}
void Reverse(char *p)
{
stack<char> S;
for (int i = 0; i<strlen(p); i++)
S.push(p[i]);
for (int i = 0; i<strlen(p); i++)
{
p[i] = S.top();
S.pop();
}
}
我收到错误strcpy_s不带2个参数。
#include <iostream>
#include <cstring>
#include <string>
#include <stack>
using namespace std;
void Reverse(char *p)
{
stack<char> S;
for (int i = 0; i<strlen(p); i++)
S.push(p[i]);
for (int i = 0; i<strlen(p); i++)
{
p[i] = S.top();
S.pop();
}
}
int main()
{
string object;
cout << "Please enter a line of text.\n";
cin >> object;
char * point = new char[object.length() + 1];
strcpy_s(point, object.c_str());
Reverse(point);
printf(" %s", point);
system("pause");
return 0;
}
答案 0 :(得分:1)
char * point = new char[object.length()+1];//+1 for the null terminator
strcpy(point, object.c_str());
Reverse(point);
printf("%s",point);
为点分配空间然后复制http://en.cppreference.com/w/cpp/string/byte/strcpy并且您正在调用Reverse,就像这个Reverse(char)
一样,您需要使用char变量的名称来调用它,就像这个Reverse(point);
一样,因为我们分配了空间我们我们完成使用后需要将其删除。
答案 1 :(得分:-1)
请检查以下修改后的代码。我现在可以反转输入字符串。
#include <iostream>
#include <string>
#include <stack>
using namespace std;
void Reverse(char *p)
{
stack<char> S;
for (int i = 0; i<strlen(p); i++)
S.push(p[i]);
for (int i = 0; i<strlen(p); i++)
{
p[i] = S.top();
S.pop();
}
}
int main()
{
string object;
cout << "Please enter a line of text.\n";
cin >> object;
char * point = new char[object.length() + 1];
strcpy(point, object.c_str());
Reverse(point);
printf(" %s", point);
system("pause");
return 0;
}