我正在编写一个程序来使用堆栈反转字符串。我的代码中出现了 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>>对象上的错误说初始问题没有运算符与操作数匹配
#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;
}
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 并且您像这样调用 ReverseReverse(char)
您需要像这样使用 char 变量的名称调用它Reverse(point);
因为我们分配了空间,我们需要在完成使用它后删除它。
请检查下面的修改代码。我现在可以反转输入字符串。
#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;
}